I have a radiobutton with two options: one is called "yes" and the other button is called "no". Clicking the "yes" button opens a div with another radiobutton, clicking the "no" button hides the div with the radio button; What I need is to keep what is selected in the radio button that is in the div when it is displayed, since if it is hidden and returned and displayed, what I selected does not appear:
Code: https://codesandbox.io/s/elated-dew-75dwf0?file=/src/App.js:0-1747
Code:
import React, { useState } from "react";
function Pruebas() {
const [value2, setValue2] = useState("no");
return (
<div>
<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">
<div className="form-check">
<input
className="form-check-input"
type="radio"
name="radio1_div"
value="div_no"
/>
<label className="form-check-label">DIV_NO</label>
<input
className="form-check-input"
type="radio"
value="div_si"
name="radio1_div"
/>
<label className="form-check-label">DIV_SI</label>
</div>
</div>
</div>
)}
</div>
</div>
);
}
export default Pruebas;
I think a possible solution is to add a new state (I called it
value
, give it whatever name you want) for these two checkboxes, and add the propertychecked
equal to a boolean that, in whatever case (div_yes or div_no), shows the one that check that corresponds, checked