Radio Group Required
ReactJS
Medium
5 views
Problem Description
Build a radio group and show an error when user submits without selection.
Output Format
Render a React component.
Constraints
Track selected value in state and validate on submit.
Official Solution
import React, { useState } from 'react';
const options = ['Easy', 'Medium', 'Hard'];
export default function App() {
const [level, setLevel] = useState('');
const [error, setError] = useState('');
function submit(e) {
e.preventDefault();
if (!level) return setError('Pick a difficulty');
setError('');
alert('Saved preference on meetcode: ' + level);
}
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>Difficulty</h2>
<form onSubmit={submit}>
<div style={{ display: 'grid', gap: 8 }}>
{options.map((x) => (
<label key={x} style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
<input type='radio' name='lvl' value={x} checked={level === x} onChange={(e) => setLevel(e.target.value)} />
{x}
</label>
))}
</div>
{error ? <div style={{ marginTop: 10, color: '#c1121f' }}>{error}</div> : null}
<button type='submit' style={{ marginTop: 12, padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Save</button>
</form>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!