I have two radio buttons: radio1
and radio2
, and one select
input.
The Select values depend on the radio buttons.
I want to set the select
value to 1
whenever I select radio1
.
I've tried setting defaultValue
and value
to the select
input but every time I switch back to radio1
from radio2
, the value is always set to 2
.
Here's my code, any help is truly appreciated:
import "./styles.css";
import { useState } from "react";
const selectItems = {
name: "size",
fields: {
radio1: [
{
value: "1"
},
{
value: "2"
}
],
radio2: [
{
value: "2"
},
{
value: "3"
},
{
value: "4"
}
]
}
};
const App = () => {
const [values, setValues] = useState({ radio: "radio1", select: "2" });
const handleChange = (name, value) => {
setValues((s) => {
return { ...s, [name]: value };
});
};
return (
<div className="App">
<h2>
How do I make the Select always be '1' when Radio1 is selected after
selecting Radio2?
</h2>
<input
type="radio"
id="radio1"
value="radio1"
name="radio"
onChange={() => handleChange("radio", "radio1")}
/>
<label htmlFor="radio1">Radio1</label>
<input
type="radio"
id="radio2"
value="radio2"
name="radio"
onChange={() => handleChange("radio", "radio2")}
/>
<label htmlFor="radio2">Radio2</label>
<br />
<select
id="size"
name="size"
onChange={(e) => handleChange("select", e.target.value)}
>
{selectItems.fields[values.radio].map(({ value }) => {
return (
<option key={value} value={value}>
{value}
</option>
);
})}
</select>
</div>
);
};
export default App;