Home > Enterprise >  React changing state of mapped component
React changing state of mapped component

Time:10-26

By clicking on the Button it should change checked state to true and apply checked style , in my case that is not happening. How to change state for mapped component? In given example i have 3 options, but i will have more than 20

export function Test() {
    const [checkedState, setChecked] = React.useState(false);
    const handleChange = () => {
        setChecked((checked) => !checked);
    };
                    <View>
                        <ButtonList
                            options={[
                                { label: "Label", value: "value" },
                                { label: "Label", value: "value2" },
                                { label: "Label", value: "value3" },
                            ]}
                        />
                    </View>
    );
}

Here i map through

type Option = {
    label: string;
    value: string;
};

type ButtonListProps = {
    options: Option[];
    value: string;
};

export function ButtonList({ options, value }: ButtonListProps) {
    return (
        <View>
            {options.map((option) => (
                <Button
                   checked={checkedState}
                   onChange={handleChange}
                   onPress={ignore}
                   key={option.value}
                   label={option.label}
                />
            ))}
        </View>
    );
}

My Button component

type ButtonProps = {
    checked: boolean;
    label?: string;
    onPress?: () => void;
    onChange?: () => void;
};

export function Button({ checked, label, onPress, onChange }: ButtonProps) {
return (
    <Pressable
        onPress={onPress}
        onChange={onChange}
    >
        <View style={checked && {backgroundColor: "red"} />
        <Text>{label}</Text>
    </Pressable>
);

}

CodePudding user response:

checkedState must be an array of states not a boolean

const [checkedState, setChecked] = React.useState([false,false,false]);

and your handleChange function should have an argument named index

 const handleChange = (index) => {
        const newState = [...checkedState]
        newState[index] = !newState[index] 
        setChecked(newState);
 };

so your map should be like

{options.map((option,index) => (
      <Button
             checked={checkedState[index]}
             onChange={()=>handleChange(index)}
             onPress={ignore}
             key={option.value}
             label={option.label}
      />
))}

edit 1 : in case you have dynamic options you can do this

const options = [
      { label: "Label", value: "value" },
      { label: "Label", value: "value2" },
      { label: "Label", value: "value3" },
]
const [checkedState, setChecked] = React.useState(options.map(()=>false));

don't forget to pass options variable to ButtonList component:

<ButtonList
      options={options}
/>
  • Related