screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script> <script src="https://unpkg.com/@babel/standalone@7.14.7/babel.min.js"></script> </head> <body> <div id="app"></div> <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> <style> .container { max-width: 500px; margin: 0 auto; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .my-select { padding: 10px; font-size: 16px; border-radius: 5px; border: 1px solid #ccc; width: 100%; margin-bottom: 20px; } .my-image { display: block; max-width: 100%; margin-top: 20px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } </style> </body> </html>