React Js Dynamic Select Option using Fetch Api
React Js Dynamic Select Option using Fetch Api:To create a dynamic select option in ReactJS using the Fetch API, you can follow these steps. First, define a state variable to hold the options data. Then, use the useEffect hook to make a fetch request to the server using the Fetch API and update the state with the received data.
Next, render a select element and map over the options data to generate the option elements dynamically. Finally, set an onChange event handler to update the selected value in the state. This way, whenever the options data changes, the select options will be updated dynamically, providing a seamless user experience.




Thanks for your feedback!
Your contributions will help us to improve service.
How can I create a dynamic select option in Reactjs using the Fetch API?
This code snippet demonstrates how to create a dynamic select option in Reactjs using the Fetch API. The component fetches data from the specified API endpoint, sets the received data as options, and renders a select element.
When an option is selected, the corresponding image URL is displayed below the select element. The selected option and image URL are tracked using state variables. The code utilizes the useState and useEffect hooks from React.
React Js Dynamic Select Option Using Fetch Api
xxxxxxxxxx
<script type="text/babel">
const { useState, useEffect } = React;
function App() {
const [options, setOptions] = useState([]);
const [selectedOption, setSelectedOption] = useState(null); // Track selected option
const [selectedImage, setSelectedImage] = useState(null); // Track selected image
useEffect(() => {
fetchOptions(); // Fetch options when the component mounts
}, []);
const fetchOptions = async () => {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/photos"
); // Replace with your API endpoint
const data = await response.json();
setOptions(data); // Set the received data as options
} catch (error) {
console.error("Error fetching options:", error);
}
};
const handleOptionChange = (event) => {
const selectedValue = event.target.value;
setSelectedOption(selectedValue); // Update selected option
const selected = options.find(
(option) => option.title === selectedValue
);
setSelectedImage(selected?.url); // Update selected image URL
};
return (
<div className="container">
<h3>React Js Dynamic Select Option using Fetch Api</h3>
<select className="my-select" onChange={handleOptionChange}>
<option value="">Select an option</option>
{options.map((option) => (
<option key={option.id} value={option.title}>
{option.title}
</option>
))}
</select>
{selectedImage && (
<img
className="my-image"
src={selectedImage}
alt={selectedOption}
style={{
marginTop: "20px",
display: "block",
maxWidth: "100%",
}}
/>
)}
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>