I have a system where it adds options to my select element when a specific value is entered. When the value is changed it only appends more options to the select element. How do I remove the old options?
Sample Code:
const sections = ["Section 1", "Section 2"];
const sections2 = ["Section 3", "Section 4"];
const [selectedValue, setValue] = useState("");
if (selectedValue == "1") {
sections?.forEach((option) => {
const selectElement = document.getElementById(
"section"
) as HTMLSelectElement;
const optionElement = document.createElement("option");
optionElement.value = option.sectionName;
optionElement.text = option.sectionName;
selectElement?.add(optionElement);
});
} else {
sections2?.forEach((option) => {
const selectElement = document.getElementById(
"section"
) as HTMLSelectElement;
const optionElement = document.createElement("option");
optionElement.value = option.sectionName;
optionElement.text = option.sectionName;
selectElement?.add(optionElement);
});
}
return (
<form>
<select onChange={e => setValue(e)}>
<option>Section List 1</option>
<option>Section List 2</option>
</select>
<select id="section">
</select>
</form>
)
>Solution :
As mentioned in the comments by @DBS, you are not supposed to do direct DOM manipulation, in React. Instead please make use of the state and render method. Here’s how you can do that. Please make necessary changes if required:
const sections1 = ["Section 1", "Section 2"];
const sections2 = ["Section 3", "Section 4"];
const [selectedList, setSelectedList] = useState("");
const [sectionOptions, setSectionOptions] = useState([]);
useEffect(() => {
if (selectedList === "Section List 1") {
setSectionOptions(sections1);
} else if (selectedList === "Section List 2") {
setSectionOptions(sections2);
} else {
setSectionOptions([]);
}
}, [selectedList]);
return (
<form>
<select value={selectedList} onChange={e => setSelectedList(e.target.value)}>
<option value="">Select a section list</option>
<option value="Section List 1">Section List 1</option>
<option value="Section List 2">Section List 2</option>
</select>
<select id="section">
{sectionOptions.map(option => (
<option key={option} value={option}>{option}</option>
))}
</select>
</form>
);