Home > other >  Is it possible to define a state for every element in map?
Is it possible to define a state for every element in map?

Time:01-05

I'm having difficulties in defining states after mapping. It says ( React Hook "useState" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function).

CodePudding user response:

You can't define the state when you map. because it's against the roles of defining the state in react.

you always should follow the way of defining the state at the top of your file.

besides that it will be better if you defined the state at the top of your file and after you can setState for what you want inside the loop. This approach is better to follow

CodePudding user response:

There's a way to do it. Each element of your map can be represented by a component, So you will just have to set a state in this component :

const Parent = () => {
  const data = [
                 {firstname: 'Quentin', lastname: 'Smith'},
                 {firstname: 'John', lastname: 'Doe'}
               ];

  return (
    <>
     {data.map(element => <Child myProp={element} />)};
    </>
  )
}



const Child = ({myProp}) => {
  // Do whatever you want with the state
  const [myState, setMyState] = React.useState();

  return <div>firstname = {myProp.firstname}, lastname = {myProp.lastname}</div>; 
}
  •  Tags:  
  • Related