screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel"> const { useState } = React; function App() { const [selectedAnswers, setSelectedAnswers] = useState({}); const handleOptionChange = (questionId, optionId) => { setSelectedAnswers(prevSelectedAnswers => ({ ...prevSelectedAnswers, [questionId]: optionId })); }; const questions = [ { id: 1, question: 'What is the capital of Australia?', options: [ { id: 1, text: 'Sydney' }, { id: 2, text: 'Melbourne' }, { id: 3, text: 'Canberra' }, { id: 4, text: 'Perth' } ] }, { id: 2, question: 'Who painted the Mona Lisa?', options: [ { id: 5, text: 'Pablo Picasso' }, { id: 6, text: 'Leonardo da Vinci' }, { id: 7, text: 'Vincent van Gogh' }, { id: 8, text: 'Michelangelo' } ] }, { id: 3, question: 'Which is the largest ocean on Earth?', options: [ { id: 9, text: 'Atlantic Ocean' }, { id: 10, text: 'Indian Ocean' }, { id: 11, text: 'Arctic Ocean' }, { id: 12, text: 'Pacific Ocean' } ] }, { id: 4, question: 'Who wrote the play "Hamlet"?', options: [ { id: 13, text: 'William Shakespeare' }, { id: 14, text: 'George Bernard Shaw' }, { id: 15, text: 'Arthur Miller' }, { id: 16, text: 'Tennessee Williams' } ] }, { id: 5, question: 'Which country is known as the "Land of the Rising Sun"?', options: [ { id: 17, text: 'China' }, { id: 18, text: 'Japan' }, { id: 19, text: 'Thailand' }, { id: 20, text: 'South Korea' } ] } ]; return ( <div className='container'> <h3>React Js handle multiple radio button in map function</h3> {questions.map(question => ( <div key={question.id}> <p>{question.question}</p> {question.options.map(option => ( <label key={option.id}> <input type="radio" name={`question_${question.id}`} value={option.id} checked={selectedAnswers[question.id] === option.id} onChange={() => handleOptionChange(question.id, option.id)} /> {option.text} </label> ))} </div> ))} <button onClick={() => console.log('Selected answers:', selectedAnswers)}>Submit</button> </div> ); } ReactDOM.render(<App />, document.getElementById("app")); </script> <style> * { box-sizing: border-box; } .container { margin: 0 auto; width: 600px; text-align: center; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.12), 0 2px 4px 0 rgba(0, 0, 0, 0.24); padding: 20px; } h3 { font-size: 20px; margin-bottom: 10px; } label { display: flex; align-items: center; margin-bottom: 10px; cursor: pointer; } input[type="radio"] { margin-right: 10px; } </style> </body> </html>