bhylu.com

Advertisements

React Select

Let option values represent stable domain choices and handle the unselected state deliberately.

How it works

A controlled select uses the select element’s value. The chosen option’s value should identify the choice independently of its visible label or current position. Here a collection window has a stable code and a readable time. An empty option means that the user has not chosen yet. The interface can show a useful summary without pretending that a time has been reserved.

Run the code

Use a separate empty lab folder with Node 22.12+ in the 22 series. Save the files below using their displayed paths; browsers may download only the basename, so create src, public or tests folders as listed. The pinned project uses React and React DOM 19.3.1 with Vite 7.3.1. Run npm install, then npm run dev and open the local address Vite prints. React examples do not run in Bhylu’s current playground.

No Apache, MySQL or change to Bhylu’s server configuration is needed. These are local teaching projects, not a publishing package. Keep generated dependencies and lockfiles in your own lab. Review the project setup.

Example

src/main.jsx

import React, { StrictMode, useState } from 'react';
import { createRoot } from 'react-dom/client';
import './style.css';

function App() {
  const [slot, setSlot] = useState('');
  const labels = { early: '10:00–11:00', late: '11:00–12:00' };
  return (
    <main>
      <h1>Neighbourhood lending desk</h1>
      <label>
        Collection window
        <select value={slot} onChange={(event) => setSlot(event.target.value)}>
          <option value="">Choose a window</option>
          <option value="early">10:00–11:00</option>
          <option value="late">11:00–12:00</option>
        </select>
      </label>
      <output>{slot ? 'Draft window: ' + labels[slot] : 'No window chosen'}</output>
    </main>
  );
}

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>,
);

Expected result

Choosing late shows “Draft window: 11:00–12:00”.

The select owns the selected value; individual options do not need selected attributes. A submitted value still needs server-side allow-list validation, because browser controls can be modified. For multiple selections, value is an array and the change handler reads selectedOptions. Do not add that complexity unless the user actually needs to choose several values.

For API contracts and version differences, use React’s official documentation.