Home > OS >  Child component not re rendering after Parent state changes
Child component not re rendering after Parent state changes

Time:09-16

I have a RadioGroup component that contains multiple RadioButton components. Here's the code for the RadioGroup component:

const RadioGroup = ({radioGroupData}) => {
    const [radioGroupRefreshData, setRadioGroupRefreshData] = useState(radioGroupData);

    const handleClick = (index) => {
        setRadioGroupRefreshData(radioGroupRefreshData.map((obj, i) => {
            if(i !== index) {
                return {text: obj.text, isSelected: false};
            }
            return {text: obj.text, isSelected: true};
        }));
    };

    return (
        <View style={styles.container}>
            {
                radioGroupRefreshData.map((obj, i) => {
                    return <RadioButton index={i}
                                        text={obj.text}
                                        isSelected={obj.isSelected}
                                        onClick={handleClick} />
                })
            }
        </View>
    );
}

The RadioGroup component has a state variable (an array) called radioGroupRefreshData. when each RadioButton is defined inside the RadioGroup, the handleClick function is passed as a prop in order to be called when a RadioButton is clicked. Here is the code for the RadioButton component:

const RadioButton = (props) => {
    const [isSelected, setIsSelected] = useState(props.isSelected);

    const initialRenderDone = useRef(false);
    useEffect(() => {
        if(!initialRenderDone.current) {
            initialRenderDone.current = true;
        }
        else {
            props.onClick(props.index);
        }
    }, [isSelected]);

    const handlePress = () => {
        if(!isSelected) {
            setIsSelected(true);
        }
    }

    return (
        <TouchableOpacity style={styles.outsideContainer} onPress={handlePress}>
            <View style={styles.radioButtonContainer}>
                { (isSelected) && <RadioButtonInnerIcon width={15} height={15} fill="#04004C" /> }
            </View>
            <Text style={styles.radioButtonText}>{props.text}</Text>
        </TouchableOpacity>
    );
}

From what I know, each RadioButton component should re render when the Parent's variable radioGroupRefreshData changes, but the RadioButton component's are not re rendering.

Thank you in advance for any help that you can give me!

CodePudding user response:

Since you have a state in RadioButton you need to update it when the props change. So in RadioButton add useEffect like this:

useEffect(() => {
    setIsSelected(props.isSelected);
},[props.isSelected]);

Also you don't have to mix controlled and uncontrolled behaviour of the component: do not set RadioButton state inside RadioButton since it comes from the RadioGroup

CodePudding user response:

you might need to provide key prop to RadioButton component

  • Related