Show an input field corresponding to radio button selection

Viewed 32
const next = useRef(false);
const [validate,setValidate] = useState(false);
const [data, setData] = useState(healthform);

return (
  <div>
    <div class="hQ">
        Have you travel anywhere before? 
    </div>
    <div class="hA">
        <Radio name={"travAny"} value={data.traAny} onChange={(val,name,isValid)=>{ 
          data[name]=val;
          valids[name]=isValid;
        }} /> 
    </div>
        {(data.traAny && data.traAny !== "0") && <Input placeHolder="If yes, please list all countries: " value={data.traAnyDet} name="traAnyDet" onChange={(val, name, isValid) => {
            data[name] = val;
            valids[name] = isValid;
        }} />} 
  </div>
);
  

I want to only display the input field as we select yes on radio button. I tried. But it doesn't show on the time that we pick yes. It only displays when it is already yes.

1 Answers

Looking at your code. I think the problem is with how you update the values. You are directly mutating the state object instaed of updating it using the setState function. I think changing the way you update the data to a solution like the one below will fix your issue:-

const [data, setData] = useState(healthForm)

 <Radio name={"travAny"} value={data.traAny} onChange={(val,name,isValid)=>{ 
        setData(prevData=>({...prevData, [name]:val, }))
      }} />

You should do the same for the valids.

Related