React Js Dynamic Select Option using Array
React Js Dynamic Select Option using Array:This code snippet demonstrates how to create a dynamic select option in a Reactjs application using an array of countries. It utilizes the useState hook from React to manage the selected option state.
The array "countries" contains objects representing different countries, each with a unique ID and name. The handleChange function is triggered when the select element's value changes, updating the selectedOption state accordingly.
The select element is rendered with options dynamically generated from the countries array using the map function. When an option is selected, the selected country is displayed below.

written

reviewed

updated

Thanks for your feedback!
Your contributions will help us to improve service.
How can I create a dynamic select option in Reactjs using an array?
This code snippet demonstrates how to create a dynamic select option using React.js and an array of countries. The useState
hook is used to manage the selected option state. An array of country objects is defined, and a select element is rendered with options generated from the array.
The handleChange
function updates the selected option state when the user makes a selection. The selected option is displayed below the select element.
React Js Dynamic Select Option using Array Example
Copied to Clipboard
xxxxxxxxxx
<script type="text/babel">
const { useState } = React;
function App() {
const [selectedOption, setSelectedOption] = useState("");
const countries = [
{ id: 1, name: "USA" },
{ id: 2, name: "Canada" },
{ id: 3, name: "United Kingdom" },
// Add more countries as needed
];
const handleChange = (event) => {
setSelectedOption(event.target.value);
};
return (
<div className="container">
<h3>React Js Dynamic Select Option using Array</h3>
<select
className="select-element"
value={selectedOption}
onChange={handleChange}
>
<option className="option-element" value="">
Select a country
</option>
{countries.map((country) => (
<option
className="option-element"
key={country.id}
value={country.name}
>
{country.name}
</option>
))}
</select>
<p className="selected-country">
Selected country: {selectedOption}
</p>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
Output of React Js Dynamic Select Option using Array
Ad