I have radio buttons followed by select dropdown. Each radio button is associated with a set of options related to it. Whenever the radio button is changed, the option in the dropdown also should change. But the problem I am facing is the option is not getting reset if the values of options are the same.
this is the data
const data = [
{
name: "option1",
info: [1, 2, 3, 4, 5]
},
{
name: "option2",
info: [1, 2, 3, 4, 5]
},
{
name: "option3",
info: [6, 7, 8, 9, 10]
}
];
I have created an example link here. Link(https://codesandbox.io/s/react-hello-world-forked-rnwe2?file=/src/index.js)
This is built on ReactJS.
But the problem I am facing is the option is not getting reset if the values of options are the same.
I'm assuming this means that you'd like the dropdown to reset to the first index each time the radio button is changed. Right now, the DOM is in control of what's currently selected, so if, say, the 3rd item in the dropdown list is selected, the DOM will store that the 3rd item has value selected. React is just changing what values are in each item when you change the option (see reconciliation), it's not actually recreating the select node in the DOM.
For this, I suggest making the select element controlled, e.g.
import React, { useState } from "react";
import ReactDOM from "react-dom";
function App() {
const [current, setCurrent] = useState(1);
const [selected, setSelected] = useState("");
const data = [
{
name: "option1",
info: [1, 2, 3, 4, 5]
},
{
name: "option2",
info: [1, 2, 3, 4, 5]
},
{
name: "option3",
info: [6, 7, 8, 9, 10]
}
];
function handleChange(id) {
setCurrent(id);
setSelected("");
}
function handleSelected(event) {
setSelected(event.target.value);
}
return (
<div>
{data.map((item, key) => {
return (
<label key={key}>
<input
type="radio"
name="test"
checked={key === current ? true : false}
onChange={(e) => handleChange(key)}
value={key}
/>
{item.name}
</label>
);
})}
<hr />
<br />
<select
value={selected}
style={{ width: "100px", padding: 10 }}
onChange={handleSelected}
>
{data[current].info.map((item, key) => {
return <option>{item}</option>;
})}
</select>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
https://codesandbox.io/s/react-hello-world-forked-d9cuh?file=/src/index.js