Skip to content

Event Handling and State in React

We’ve assembled our resource directory from components and worked on its appearance. Let’s try using it. We can type into Search and check Open now, but the rest of the interface doesn’t know what we’ve done. The category buttons don’t remember a selection either.

In this lesson, we’ll give our components that memory. We’ll use state to keep track of input and event handlers to update it. Our first goal is deliberately small: make the controls respond and show what they remember. Connecting Filters to Results comes in Lesson 13.

At the end of this class, you should be able to…

  • Attach click, change, and submit handlers through JSX.
  • Use useState to retain a string, an array, and a boolean between renders.
  • Control text inputs with value and checkboxes with checked.
  • Calculate a new array from previous state without modifying the old array.
  • Explain which component owns a piece of local state.
Interaction What we should see
Type into Search A preview repeats the current search term
Select a category Its button shows that it is selected
Select that category again Its highlight disappears
Choose All The category selection becomes empty
Check Open now A preview changes from No to Yes
Submit the form The browser logs the current values without reloading

A normal local variable is created again each time React calls our component. useState gives us a value that React remembers and a function that requests an update:

const [searchTerm, setSearchTerm] = useState('');

We read searchTerm while rendering. An event handler calls setSearchTerm with the next value. React then renders with that value. Calling the setter doesn’t change the variable in the handler that’s already running. See React’s useState reference.

Call hooks at the top level of a component or custom hook, before any conditional returns. Don’t put a useState call inside a click handler, loop, or if statement.

An uncontrolled input already lets us type. A controlled input also makes its current value available to our React code. We supply value and an onChange handler; for a checkbox, we supply checked and read event.target.checked. React’s input reference compares the two approaches.

We don’t need to query the DOM or change classes ourselves. JSX describes what the interface should look like for the current state.


From the root of your workbook, grab the starter for your section. If you already have today’s starter, continue with that copy.

Terminal window
pnpm dlx tiged --disable-cache --force DG-InClass/SDEV-2150-A01-Sep-2026/sk/day-12/example/lesson-12-starter ./src/lesson-12
Terminal window
cd src/lesson-12/frontend
pnpm install
pnpm dev

Open the URL printed by Vite. The starter already includes React, Tailwind, and DaisyUI. Its resource data is local, so we don’t need the backend today.

All file paths below start inside src/lesson-12/frontend. We’ll work in src/components/Filters.jsx; leave the existing layout and resource data in place.

  1. Give Filters a value to remember.

    Import useState and declare the search state inside the component, before its return.

    src/components/Filters.jsx
    import { useState } from 'react';
    import Card from './ui/Card';
    // src/components/Filters.jsx
    export default function Filters() {
    const [searchTerm, setSearchTerm] = useState('');
    return (

    Now find the input with id="q". Keep its placeholder and styling, and add the two props below.

    src/components/Filters.jsx
    <input
    id="q"
    type="text"
    value={searchTerm}
    onChange={(e) => setSearchTerm(e.target.value)}
    placeholder="Try: tutoring, mental health, bursary"

    The arrow function is our event handler. React calls it when the input changes, and e.target.value supplies the current text.

  2. Make the state visible outside the input.

    Find the end of the Search input’s containing <div>, just before the first horizontal rule. Add a preview there.

    src/components/Filters.jsx
    placeholder="Try: tutoring, mental health, bursary"
    className="w-full rounded border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder-gray-400 focus:border-sky-500 focus:outline-none focus:ring-2 focus:ring-sky-200"
    />
    </div>
    <p className="text-sm text-base-content/70">
    Searching for: {searchTerm || '(nothing yet)'}
    </p>
    <hr className="border-gray-200" />

    Type tutoring, then delete it. The preview should follow each change. Results stays the same: this state belongs to Filters, and we haven’t shared it with another component.

  3. Remember multiple category selections.

    Add another state variable and a handler below searchTerm.

    src/components/Filters.jsx
    export default function Filters() {
    const [searchTerm, setSearchTerm] = useState('');
    const [selectedCategories, setSelectedCategories] = useState([]);
    function toggleCategory(category) {
    setSelectedCategories((previous) => {
    if (category === 'All') return [];
    if (previous.includes(category)) {
    return previous.filter((item) => item !== category);
    }
    return [...previous, category];
    });
    }
    return (

    The next array depends on the previous array, so we pass an updater function to the setter. filter and the spread syntax create new arrays. We don’t use push or splice on the state array.

    Our category contract is simple: an empty array means All. We never store the word 'All' alongside actual categories.

  4. Connect the category buttons.

    Find the button inside the category .map(). Replace its class and add a handler and pressed state. The starter already has type="button", which prevents category clicks from submitting the form.

    src/components/Filters.jsx
    key={label}
    type="button"
    className="rounded border border-sky-600 px-3 py-1 text-xs font-semibold text-sky-700 hover:bg-sky-50"
    className={`btn btn-sm ${
    (label === 'All'
    ? selectedCategories.length === 0
    : selectedCategories.includes(label))
    ? 'btn-primary' : 'btn-outline'
    }`}
    aria-pressed={label === 'All'
    ? selectedCategories.length === 0
    : selectedCategories.includes(label)}
    onClick={() => toggleCategory(label)}
    >
    {label}

    Click Academic, then Wellness. Both should remain selected. Click Academic again, then All. All should become the only highlighted button. aria-pressed also communicates the toggle state to assistive technology.

    We pass a function to onClick. Writing onClick={toggleCategory(label)} would call our handler while rendering, before the user clicks anything.

  5. Control a checkbox with a boolean.

    Add the boolean alongside our other state.

    src/components/Filters.jsx
    const [searchTerm, setSearchTerm] = useState('');
    const [selectedCategories, setSelectedCategories] = useState([]);
    const [openNowOnly, setOpenNowOnly] = useState(false);

    Find the checkbox with id="openNow".

    src/components/Filters.jsx
    type="checkbox"
    id="openNow"
    checked={openNowOnly}
    onChange={(e) => setOpenNowOnly(e.target.checked)}
    className="h-4 w-4 rounded border-gray-300 text-sky-600 focus:ring-sky-500"

    Extend our preview so we can see the boolean change.

    src/components/Filters.jsx
    <p className="text-sm text-base-content/70">
    Searching for: {searchTerm || '(nothing yet)'}
    {' | '}Open now only: {openNowOnly ? 'Yes' : 'No'}
    </p>

    Check and uncheck Open now. The preview should alternate between Yes and No. A checkbox’s value is not its checked state; that’s why we read checked here.

  6. Handle submission without navigating away.

    Add a submit handler immediately before the component’s return.

    src/components/Filters.jsx
    function handleSubmit(e) {
    e.preventDefault();
    console.log('Filters submitted', {
    searchTerm,
    selectedCategories,
    openNowOnly,
    });
    }
    return (
    <Card title="Filters">
    <div className="space-y-4 p-4">
    <form id="frm-filter" className="space-y-4">
    <form onSubmit={handleSubmit} id="frm-filter" className="space-y-4">

    Open the browser console, enter some values, and click Filter. Try pressing Enter in Search as well. Both should log the current values without reloading the page. Submitting on the form covers both interactions.

    The handler reports our state; it doesn’t filter the resource list yet.

Try the controls using Tab, Space, and Enter. Then explain the sequence: a user acts, a handler requests a state change, and React renders the new state. Which line connects each input back to the value React remembers?

We’ve made Filters interactive using local state. In the next lesson, we’ll let sibling components use that information.


Complete these small tasks in the resource directory without lifting state out of its current component.

  • Make Reset restore the search term, category array, and Open now state. Reset is already a type="button"; give it a click handler that resets the React values.
  • Control Virtual options with its own boolean state. Include it in the preview, submitted values, and Reset behaviour.
  • In Results.jsx, track the selected resource locally, initially null. Pass an onClick callback and a selected boolean to each ResultsItem.
  • Update ResultsItem.jsx to accept those props and provide a native button for selecting the resource. Keep the <li> as the list item and make the title button keyboard accessible. Use the selected prop to highlight the item and expose its pressed state.
  • Show the selected resource’s title beneath the results list. Check src/data/resources.js: the property is title, not name.

You should be able to select an item by mouse or keyboard and see exactly one highlight. Details will still show its original content. Connecting that panel is our next task.

Continue your existing Users and Posts project, following homework.md in today’s starter. Keep the layout and DaisyUI work from Lesson 11.

Your task is to create a UserSearch component with a controlled input and a submit handler, and add local selected-user state to Users. Submitting should log a message without reloading; selecting a user should visibly highlight that user.

For this exercise, keep the search state in UserSearch and the selected-user state in Users. Searching the list and connecting selection to posts come later.

Before finishing, verify that:

  • Typing changes the React state and submitting doesn’t reload the page.
  • Selecting another user moves the highlight, including when using the keyboard.
  • Your existing layout still works at narrow and wide widths.
  • Your README.md explains where each state value lives and gives one event-handler example.

Review your changes, then commit and push your workbook work as directed in homework.md.