'React Boostrap Select, First Select Option ins not triggered by onChange event
I'm using React Boostrap Select component :
<Form.Group className="mb-1">
<Form.Label
htmlFor="type"
className="iig-form-label d-inline-block text-truncate"
>
Type de projet
{loadingTypes && <Spinner animation="grow" size="sm" />}
</Form.Label>
<Form.Select
required
aria-label="Default select example"
id="type"
name="type"
onChange={(e) => handleChange(e)}
isInvalid={false}
>
// THIS IS THE DEFAULT OPTION THAT IS NOT TRIGGERED <-------------------
<option
value={currentType ? currentType["@id"] : ""}
data-category={
currentType ? currentType?.category?.label : ""
}
>
{currentType
? currentType.label
: `Choisir parmi la
liste des types de projets`}
</option>
{filteredTypes.map((filteredTypes, key) => {
return (
<option
value={`/api/types/${filteredTypes.id}`}
data-category={filteredTypes.category.label}
key={key}
>
{filteredTypes.label}
</option>
);
})}
I added a default option to show.
When I click on the default option the onChange
event is not triggered.
How can I fix that?
Solution 1:[1]
I couldn't follow your example, so I created a minimal example to show you how it works:
- Create state to store the value and give the id/value of the selected option you want to see initially as default value
- Write onChange handler
- Pass state value and onChange handler to Form.Select
- In Form.Select iterate over you select options list
.
const selectOptions = [
{ value: "js", label: "Javascript" },
{ value: "ja", label: "Java" },
{ value: "py", label: "Python" },
{ value: "go", label: "Go" },
{ value: "cs", label: "C#" }
];
export default function App() {
const [value, selectValue] = useState("js");
const handleChange = (event) => selectValue(event.target.value);
return (
<Form.Group className="mb-1">
<Form.Select value={value} onChange={handleChange}>
{selectOptions.map((option) => {
return <option value={option.value}>{option.label}</option>;
})}
</Form.Select>
</Form.Group>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Igor Gonak |