Encountering type errors in React+Typescript while dynamically setting values in the change handler

I am currently working on dynamically generating a form based on an array of objects.

The objective is to allow users to create accounts dynamically by clicking the Add User button and then submit the complete state object of users to the backend.

Encountering this particular error 'Element implicitly has an 'any' type because type '{ name: string; age: string; }' has no index signature'.

I have limited experience with React! Any assistance would be greatly appreciated.

Could you help me identify what I might be doing incorrectly?

import * as React from "react";

interface State{
  users:User[]
}
interface Props{

}
interface User{
  name:string,
  age:number;
}

class App extends React.Component<Props,State> {

   state = {
      users: [{name:"", age:""}],
   }

   handleChange = (value:number,event  : React.ChangeEvent<HTMLInputElement>) => {
    let users = [...this.state.users];
    console.log(event.target.value);
    users[value][event.target.name] = event.target.value;
    this.setState({ users }, () => console.log(this.state.users))
   }

   addUser = () => {    
    this.setState((prevState) => ({
      users: [...prevState.users, {name:"", age:""}],
    }));
   }

   handleSubmit = (e:any) => { 
       e.preventDefault();
       console.log(this.state.users) 
   }

   render() {
     let { users} = this.state
     return (
      <form onSubmit={this.handleSubmit} >
        <button onClick={this.addUser}>Add new cat</button>
        {
          users.map((val, id)=> {
            return (
              <div key={id}>
                <input
                  type="text"
                  name="name"                 
                  value={users[id].name}                   
                  onChange = {(e) =>this.handleChange(id,e)}
                />

                <input
                  type="text"
                  name="age"
                  value={users[id].age}                  
                  onChange = {(e) => this.handleChange(id,e)}
                />
              </div>
            )
          })
        }
        <input type="submit" value="Submit" /> 
      </form>
    )
  }
}
export default App;

Answer №1

When you try to access the value of event.target.value, keep in mind that it may not always be a string matching either 'name' or 'age'. This can lead to issues when assigning values like:

users[value][event.target.name] = event.target.value;

To address this uncertainty, TypeScript suggests updating the User interface as follows:

interface User {
    name: string,
    age: number;
    [key: string]: string | number
}

Alternatively, you can validate the key before setting the value:

const keyName = event.target.name
if (keyName === 'name' || keyName === 'age') {
    users[value][keyName] = event.target.value;
}

Answer №2

The User interface is incorrect because the age property is being cast to a number, and then set to an empty string "".

Additionally, when using the Array.prototype.map method, the index [id] is not utilized correctly in your implementation of the map() function. According to MDN:

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

For more information about map, you can visit this link: here

import * as React from "react";

interface Props{

}

interface User {
  name: string;
  age: number | string;
}

interface State {
  users: User[];
}

class App extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {
      users: [{ name: "", age: "" }]
    };
  }

  handleChange = (value: number, event: React.ChangeEvent<HTMLInputElement>) => {
    let users = [...this.state.users];
    users[value][event.target.name] = event.target.value;
    this.setState({ users }, () => console.log(this.state.users));
  };

  addUser = () => {
    this.setState(prevState => ({
      users: [...prevState.users, { name: "", age: "" }]
    }));
  };

  handleSubmit = (e: any) => {
    e.preventDefault();
    console.log(this.state.users);
  };

  render() {
    const { users } = this.state;
    return (
      <form onSubmit={this.handleSubmit};
        <button onClick={this.addUser}>Add new cat</button>
        {users.map((user, id) => {
          return (
            <div key={id}>
              <input
                type="text"
                name="name"
                value={user.name}
                onChange={e => this.handleChange(id, e)}
              />

              <input
                type="text"
                name="age"
                value={user.age}
                onChange={e => this.handleChange(id, e)}
              />
            </div>
          );
        })}
        <input type="submit" value="Submit" />
      </form>
    );
  }
}
export default App;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The SeekTo function in react-player is not working as expected

I've been encountering some difficulties while using the seekTo function with react-player in my next.js site. Whenever I attempt to use it, an error pops up saying: "playerRef.seekTo is not a function." I also tried using "playerRef.current.seekTo(p ...

Is it secure to store information that impacts component rendering within a JWT payload?

I am currently developing a MERN app where users have various roles, and different components are rendered based on their role in React. In my application, I store a JWT containing the user's ID and role in a cookie, which is then decoded in a global ...

Is it possible to imitate the window.alert function in jest testing?

In my React component, I have the following setup: class Form extends React.Component { constructor(props) { super(props); this.state = this._createEmptyTodo(); } render() { this.i18n = this.context; return ( ...

Having difficulty running strapi and react at the same time

I encountered issues when attempting to run both strapi and react concurrently in the public directory of strapi. [1] npm ERR! code ELIFECYCLE [1] npm ERR! errno 1 [1] npm ERR! [email protected] start: `react-scripts start` [1] npm ERR! Exit status ...

Tips for retrieving and presenting information from a JSON document in a React TypeScript application

I am struggling to display data in a list format using TypeScript. I am able to fetch the data but unable to display it properly. I am currently using map to iterate through an array of JSON objects. //json file [ { "id": "6s", ...

Component not being returned by function following form submission in React

After spending a few weeks diving into React, I decided to create a react app that presents a form. The goal is for the user to input information and generate a madlib sentence upon submission. However, I am facing an issue where the GenerateMadlib compone ...

Here is a guide on sorting through data within an array of objects using React.js and Typescript

How can I filter dealers' data based on the minimum and maximum price range of a slider change? I am retrieving dealers' data using an API and storing the slider's min and max values in a handle change function. What is the best way to filte ...

Experimenting with TypeScript Single File Component to test vue3's computed properties

Currently, I am in the process of creating a test using vitest to validate a computed property within a vue3 component that is implemented with script setup. Let's consider a straightforward component: // simple.vue <script lang="ts" set ...

The TypeScript error occurs when attempting to assign a type of 'Promise<void | Object>' to a type of 'Promise<Object>' within a Promise.then() function

I'm currently working on a service to cache documents in base64 format. The idea is to first check sessionStorage for the document, and if it's not there, fetch it from IRequestService and then store it in sessionStorage. However, I've encou ...

Exploring the capabilities of using Next.js with grpc-node

I am currently utilizing gRPC in my project, but I am encountering an issue when trying to initialize the service within a Next.js application. Objective: I aim to create the client service once in the application and utilize it in getServerSideProps (wit ...

Steps for importing a CommonJS module that exports as a callable into TypeScript

I am dealing with a project that has a mixture of JavaScript and TypeScript files. Within the project, there is a JS library that follows this structure: module.exports = () => { // logic dependent on environment variables // then... return { ...

Having Trouble Retrieving Data from Observable in Angular 2 and Typescript

I've encountered a promise error when trying to access a variable that receives data from an observable. Here's an example: Within my component, I have defined the Stat class: export class Stats { name: string; percentage: number; constru ...

"Enhance the appearance of bootstrap buttons by applying CSS to add shadow and border when the

Working on a frontend project using the React framework and Bootstrap 5.3 for design. Noticing that shadows are deactivated in Bootstrap by default, which means buttons don't display shadows when active as per the Bootstrap v5.0 documentation. Link ...

Formik integration issue with MUI DatePicker causing error message: "date.isBefore is not a function"

I'm currently creating a form in React using Formik and MUI components. However, I encountered an error that says: date.isBefore is not a function TypeError: date.isBefore is not a function at DayjsUtils.isBeforeDay (http://localhost:3000/static/j ...

Error occurs when attempting to clear the cache storage

useEffect(async () => { caches.open('my-cache') }, [token, user_id]) Upon trying to log out of the application, const logoutFunc = () => { localStorage.clear() caches.keys().then((list) => list.map((key) => { ...

What is the variance in performance between the sx prop and the makeStyles function in Material UI?

I recently started delving into Material UI and learned that it employs a CSS in JS approach to style its components. I came across 2 methods in the documentation for creating styles: First, using the sx prop: <Box sx={{ backgroundColor: 'green& ...

Exploring the functionality of multiple checkboxes in Next.js 14, the zod library, shadcn/ui components, and react-hook

I'm currently working on a form for a client where one of the questions requires the user to select checkboxes (or multiple checkboxes). I'm still learning about zod's schema so I'm facing some challenges in implementing this feature. I ...

Is Next.js compatible with a custom server setup and automatic optimization for static content?

Is it feasible to utilize a custom server in conjunction with the static optimization feature offered by Next.js? I am aware that the documentation states this is not supported, but is there a potential workaround for achieving this? Find more informatio ...

The @input field is failing to show the value entered by the user

I'm having trouble with my dynamic reactive form, as the value is not showing up <div *ngFor="let deliveryAcross of (deliveriesAcross | async)!; let i = index;"> <app-delivery-across [index]="i" [deliveryAcross]= ...

Understanding how to efficiently map through FontAwesome icons using React TypeScript and effectively showcase them on the frontend

I am in the process of developing a versatile component that allows me to input the href, target, and rel attributes, along with specifying the FontAwesome Icon I want to utilize. My goal is to be able to pass multiple icons into this list, which will then ...