Sometimes, we want to get select element’s value in react-bootstrap.
In this article, we’ll look at how to get select element’s value in react-bootstrap.
How to get select element’s value in react-bootstrap?
To get select element’s value in react-bootstrap, we can set the onChange
prop to a function that gets the selected value.
For instance, we write:
import React, { useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Form } from "react-bootstrap";
export default function App() {
const [val, setVal] = useState();
console.log(val);
return (
<Form.Select value={val} onChange={(e) => setVal(e.target.value)}>
<option>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</Form.Select>
);
}
We create the val
state with the useState
hook.
Then we add a select drop down by adding the Form.Select
component.
Next, we set onChange
of the Form.Select
component to a function that calls setVal
with e.target.value
to set val
to the value attribute value of the selected option element.
As a result, we should see the selected value logged when we change the option we select from the drop down.
Conclusion
To get select element’s value in react-bootstrap, we can set the onChange
prop to a function that gets the selected value.