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 [checkboxData, setCheckboxData] = useState([]); useEffect(() => { const fetchCheckboxData = async () => { try { const response = await fetch( "https://www.fruityvice.com/api/fruit/all" ); const data = await response.json(); // Add a "checked" property to each checkbox data item const checkboxesWithChecked = data.map((checkbox) => ({ ...checkbox, checked: false, })); setCheckboxData(checkboxesWithChecked); } catch (error) { console.error("Error fetching checkbox data:", error); } }; fetchCheckboxData(); }, []); const handleCheckboxChange = (id) => { // Find the checkbox item by id const updatedCheckboxData = checkboxData.map((checkbox) => checkbox.id === id ? { ...checkbox, checked: !checkbox.checked } : checkbox ); setCheckboxData(updatedCheckboxData); console.log(updatedCheckboxData); }; return ( <div className="container"> <h3 className="heading"> React Js Dynamic Checkbox using Fetch Api </h3> {checkboxData.map((checkbox) => ( <div className="checkbox-container" key={checkbox.id}> <input type="checkbox" id={checkbox.id} checked={checkbox.checked || false} onChange={() => handleCheckboxChange(checkbox.id)} className="checkbox-input" /> <label htmlFor={checkbox.id} className="checkbox-label"> {checkbox.name} </label> </div> ))} </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); } .heading { font-size: 24px; font-weight: bold; margin-bottom: 20px; } .checkbox-container { display: flex; align-items: center; margin-bottom: 10px; } .checkbox-input { margin-right: 10px; } .checkbox-label { font-size: 16px; cursor: pointer; } .checkbox-label:hover { text-decoration: underline; } </style> </body> </html>