I'm working on what seems to be a rather odd problem and I can't quite figure out how to go about resolving it.
The Issue:
I'm working on a React.js website and I'm attempting to change the options list of on React-Select element based on the selection of another React-Select element and I'm having difficulty making this work.
The basic idea is this. Say I have two lists of genres for books. One is a list of non-fiction genres and the other of fiction genres. The two select boxes are "genre-type-select" and the other is "genre-select". The goal is to have the choice option list in genre-select be chosen based on what type of genre type I chose in the genre-type-select.
The Code:
I've omitted a large amount of code so that only the relevant material is here.
const [nonFictionGenreNamesList, setNonFictionGenreNamesList]=useState([]);
const [fictionGenreNamesList, setFictionGenreNamesList]=useState([]);
const genreSelectRef=useRef(null);
const genreOptions=[{value: "Non-Fiction", label: "Non-Fiction"}, {value: "Fiction", label: "Fiction"}];
const determineGenreSelectContents =(choice)=> {
if(choice==="Non-Fiction"){
genreSelectRef.options=[nonFictionGenreNamesList];
} else {
genreSelectRef.options=[fictionGenreNamesList];
}
}
return (
<label htmlFor="genreTypeSelect">Genre:</label>
<Select options={genreOptions} defaultValue={genreOptions[0]} id="genre-type-select" className="select-box"
onChange={(choice)=> determineGenreSelectContents(choice.value)} />
<Select ref={genreSelectRef} options={nonFictionGenreNamesList} id="genre-select" className="select-box"
onChange={(choice) => setBookGenreSelection(choice.value)}/>
);
The idea that I was on was that whenenver I selected a new genre type in the "genre-select-select", it would then trigger an onChange effect in the "determineGenreSelectContents" method that would check the chosen value and then alter the options presented in the "genre-select" box accordingly using ref.
Thoughts:
If there is a better way to do this without having to resort to useRef() then I don't know it. I would prefer to avoid the ref system if at all possible though.
One thing I could do would be to simply remove the first select-box entirely and use a grouped options list. React-select certainly allows for that and it might even be a cleaner solution overall but I was really hoping to have two clearly separated lists that could be chosen at will.
Besides, if nothing else then this is a very interesting question to solve purely for the sake of solving it. During my research, I came across this post on Stack Overflow asking something nearly identical but it was never answered nor commented on so I know I'm not the first to have had this issue before.