hide div by selecting radio button "no" - reactjs
Solution 1:
To make no as your initial radio checked value you can set default value in your useState. add a checked property based on the state value. you code will look like that
import { useState } from "react";
export default function Test() {
const [value2, setValue2] = useState("no");
return (
<>
<div className="col-sm-6">
<div className="form-check">
<input
className="form-check-input"
type="radio"
name="radio1"
value="no"
checked={value2 === "no"}
onChange={(e) => setValue2(e.currentTarget.value)}
/>
<label className="form-check-label">NO</label>
<input
className="form-check-input"
type="radio"
value="si"
name="radio1"
checked={value2 === "si"}
onChange={(e) => setValue2(e.currentTarget.value)}
/>
<label className="form-check-label">SI</label>
</div>
</div>
<div className="col-sm-7">
{value2 === "si" && (
<div className="card">
<div className="card-body">
<h1>DIV OK</h1>
</div>
</div>
)}
</div>
</>
);
}
Solution 2:
Simply remove the "checked" before "onChange" from first radio input.
<input className="form-check-input" type="radio" name="radio1" value="no" onChange={e => setValue2(e.currentTarget.value)} />
<label className="form-check-label">NO</label>
Checked is not allowing value2 to change it's value.