Custom Select Placeholder
ReactJS
Medium
7 views
Problem Description
Build a select with a placeholder option and require a real choice.
Output Format
Render a React component.
Constraints
Use an empty value placeholder and validate on submit.
Official Solution
import React, { useState } from 'react';
export default function App() {
const [topic, setTopic] = useState('');
const [error, setError] = useState('');
function submit(e) {
e.preventDefault();
if (!topic) return setError('Please choose a topic');
setError('');
alert('Chosen on meetcode: ' + topic);
}
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>Pick a topic</h2>
<form onSubmit={submit} style={{ display: 'grid', gap: 12 }}>
<select value={topic} onChange={(e) => setTopic(e.target.value)} style={{ padding: '10px 12px', borderRadius: 12, border: '1px solid ' + (error ? '#c1121f' : '#bbb') }}>
<option value=''>Select one...</option>
<option value='React'>React</option>
<option value='CSS'>CSS</option>
<option value='HTML'>HTML</option>
</select>
{error ? <div style={{ color: '#c1121f' }}>{error}</div> : null}
<button type='submit' style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Continue</button>
</form>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!