Sometimes, we want to create a dynamic drop down list with React Bootstrap.
In this article, we’ll look at how to create a dynamic drop down list with React Bootstrap.
How to create a dynamic drop down list with React Bootstrap?
To create a dynamic drop down list with React Bootstrap, we can call the option array’s map
method to return the option element for each option in the array.
For instance, we write:
import React, { useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Form } from "react-bootstrap";
const options = [
{ name: "One", id: 1 },
{ name: "Two", id: 2 },
{ name: "Three", id: 3 },
{ name: "four", id: 4 }
];
export default function App() {
const [val, setVal] = useState();
console.log(val);
return (
<Form.Select value={val} onChange={(e) => setVal(e.target.value)}>
{options.map((o) => {
const { name, id } = o;
return <option value={id}>{name}</option>;
})}
</Form.Select>
);
}
We call options.map
with a callback that returns the option element by setting the value
prop to id
and the text content to name
.
Now we should see the options One, Two, Three and Four available in the drop down.
We also set the value
prop of Form.Select
to val
and the onChange
prop to a function that calls setVal
with e.target.value
to set val
to the selected option’s value
attribute value.
Conclusion
To create a dynamic drop down list with React Bootstrap, we can call the option array’s map
method to return the option element for each option in the array.