Custom Select Placeholder

Custom Select Placeholder

Medium ReactJS Forms & Validation 24 views
Explanation Complexity

Problem Statement

Build a select with a placeholder option and require a real choice.

Input Format

No input.

Output Format

Render a React component.

Constraints

Use an empty value placeholder and validate on submit.

Input / Output Format

Input Format
No input.
Output Format
Render a React component.
Constraints
Use an empty value placeholder and validate on submit.

Examples

Input:
Output:
(React code)

Example Solution (Public)

ReactJS
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>
  );
}

Official Solution Code

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>
  );
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.