bhylu.com

Advertisements

React Multiple Form Inputs

Use one form object when fields belong together, and keep the update boundary explicit.

How it works

A small request draft can be a record with named fields. A shared change handler can use the input name to choose which field changes. This saves repetition, but it should not become an unrestricted path setter for arbitrary external data. The example accepts only the two fields defined in its markup and copies the previous record. A separate output makes both values easy to inspect.

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 [draft, setDraft] = useState({ item: '', desk: '' });
  function change(event) {
    const { name, value } = event.target;
    if (name !== 'item' && name !== 'desk') return;
    setDraft((previous) => ({ ...previous, [name]: value }));
  }
  return (
    <main>
      <h1>Neighbourhood lending desk</h1>
      <label>
        Item
        <input name="item" value={draft.item} onChange={change} />
      </label>
      <label>
        Desk
        <input name="desk" value={draft.desk} onChange={change} />
      </label>
      <output>
        {draft.item || 'No item'} at {draft.desk || 'no desk'}
      </output>
    </main>
  );
}

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

Expected result

Entering Basket and East produces “Basket at East”.

Computed property syntax updates the named field, and spread preserves the other field. The handler captures name and value before scheduling an update so the updater receives plain data rather than depending on an event object. Different input types need different extraction rules; do not force checkboxes, files and number parsing through a text-only handler.

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

Advertisements