Home > Software engineering >  In React Native, how to setState to different child component in a map
In React Native, how to setState to different child component in a map

Time:02-05

So I got 3 objects from the firebase firestore. then, I've iterated them with the map function, creating three components. When I try to update the state of the UI of one Component, the entire three components are updated as well. For example, If I press the toggle button of One component, I see that all three toggle buttons are being pressed.

Here is the relevant part of the code:`

const [toggle, setToggle] = React.useState('checked')

const handleToggle= () => setToggle(toggle === 'checked' ? 'unchecked' : 'checked')

...

function seeData(){
return info.map((data, index, ) => {

...

<ToggleButton icon={toggle === 'checked' ? 'heart-outline' : 'heart'}
    style={{backgroundColor: 'transparent'}}
     color={toggle === 'checked' ? 'black' : 'red'} value='like' status={toggle}
     onPress={handleToggle} size={30} ></ToggleButton>`

Thanks!

CodePudding user response:

Try this way as I have added isChecked flag to maintain each toggle separately for runtime reflection

export function App() {

  /* set `info` array in state default */
  const [data, setData] = React.useState(info ?? []);
  
  /* update state here */
  const handleToggle = (index) => {
    const newData = [...data];
    newData[index]["isChecked"] = newData[index]["isChecked"] ? false : true;
    setData(newData);
  };

  function seeData() {
    return data.map((data, index) => {
      <ToggleButton
        icon={data.isChecked ? "heart-outline" : "heart"}
        .....
        color={data.isChecked ? "black" : "red"}
        ....
        status={!data.isChecked ? "unchecked" : "checked"}
        onPress={() => handleToggle(index)}
        ...
      ></ToggleButton>;
    });
  }
}
  •  Tags:  
  • Related