Home > Software design >  Updating nested state in React Native when mapping over data
Updating nested state in React Native when mapping over data

Time:07-27

I am mapping over state which displays 3 radio buttons and I only want 1 out of the 3 to be selected at one time and show the selected radio button style - so just a standard behaviour.

The first radio button - isChecked is defaulted to true and I then want to be able to switch the selected styles onPress of the other radio buttons which displays an inner filled circle.

I am getting confused on how to handle the isChecked as true for only the selected Radio Button onPress. I believe I should be using the index of the map to update the state but im unsure on how to go about it.

  const [option, setOption] = useState([
    { permission: 'Standard User', isChecked: true },
    { permission: 'Approver', isChecked: false },
    { permission: 'Administrator', isChecked: false },
  ]);

  const RadioButton = ({ checked, onCheck }) => (
    <StyledRadioButton onPress={onCheck}>
      {checked && <SelectedRadioButton />}
    </StyledRadioButton>
  );


      {option.map(({ isChecked }, i) => (
          <RadioButton
            onCheck={() =>
              setOption(
                ...prev => {
                  !prev.isChecked;
                },
              )
            }
            checked={isChecked}
          />
      ))}

CodePudding user response:

Your state is an array of objects which hold a boolean flag. If the user checks a checkbox, then this flag should be set to true while all the others should be set to false. The setter of the state receives an array again, thus we could use the map function again as well as the index argument as you have suggested yourself in your question.

{option.map(({ isChecked }, i) => (
          <RadioButton
            onCheck={() =>
              setOption(
                prev => prev.map((opt, index) => ({...opt, isChecked: i === index ? true : false}))
              )
            }
            checked={isChecked}
          />
      ))}
  • Related