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, useEffect } = React function App() { const [selectedOption, setSelectedOption] = useState(''); const [error, setError] = useState(''); const handleOptionChange = (event) => { setSelectedOption(event.target.value); setError(''); }; const handleSubmit = (event) => { event.preventDefault(); if (selectedOption === '') { setError('Please select an option'); } else { alert('Successfully submitted') // Perform further actions with the selected option } }; return ( <div className='container'> <h3>React Js Radio Button Validation</h3> <form onSubmit={handleSubmit}> <div> <input type="radio" id="option1" value="option1" checked={selectedOption === 'option1'} onChange={handleOptionChange} /> <label htmlFor="option1">Option 1</label> </div> <div> <input type="radio" id="option2" value="option2" checked={selectedOption === 'option2'} onChange={handleOptionChange} /> <label htmlFor="option2">Option 2</label> </div> <div> <input type="radio" id="option3" value="option3" checked={selectedOption === 'option3'} onChange={handleOptionChange} /> <label htmlFor="option3">Option 3</label> </div> {error && <div style={{ color: 'red' }}>{error}</div>} <button type="submit">Submit</button> </form> </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 { text-align: center; margin-bottom: 20px; } form { display: flex; flex-direction: column; } div { margin-bottom: 10px; } input[type="radio"] { margin-right: 10px; } label { font-weight: 500; } button[type="submit"] { background-color: #4caf50; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; } button[type="submit"]:hover { background-color: #45a049; } div.error { color: red; margin-top: 10px; } </style> </body> </html>