I have these radio buttons for male and female. If the user has clicked 'male ', a text field will appear for the message. The problem is if I'll choose male and then type in the message and I'll choose female the next time, the value of the textfield msg is still there. How can I change it back to just nothing?
The message is still there even if I have already clicked 'male'
codesandbox: https://codesandbox.io/s/radio-button-cn9708?file=/demo.js
codes:
export default function ControlledRadioButtonsGroup() {
const [value, setValue] = React.useState("female");
const handleChange = (event) => {
setValue(event.target.value);
};
const [msg, setMsg] = React.useState("");
return (
<div>
<FormControl>
<FormLabel id="demo-controlled-radio-buttons-group">Gender</FormLabel>
<RadioGroup
aria-labelledby="demo-controlled-radio-buttons-group"
name="controlled-radio-buttons-group"
value={value}
onChange={handleChange}
>
<FormControlLabel value="female" control={<Radio />} label="Female" />
<FormControlLabel value="male" control={<Radio />} label="Male" />
</RadioGroup>
</FormControl>
{value === "male" && (
<TextField
label="msg"
value={msg}
onChange={(e) => setMsg(e.target.value)}
/>
)}
{msg} - Message
</div>
);
}
I tried this:
if (value === "female") {
setMsg("");
}
But this will show as:
Too many re-renders. React limits the number of renders to prevent an infinite loop.
Put that in the handleChange handler:
const handleChange = (event) => {
if (event.target.value === "female") {
setMsg("");
}
setValue(event.target.value);
};
You have to wrap this part into useEffect hook
React.useEffect(() => {
if (value === "female") {
setMsg("");
}
}, [value])
Try using an useEffect hook:
useEffect(() => { value === 'female' && setMsg('') }, [value])
The array in the second parameter ([value]) specifies the dependencies. If any of the dependencies change, the effect will be triggered. Just remember that it only does a shallow comparison.