Event Handling and State in React
Lecture
Section titled “Lecture”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.
Learning Outcome Guide
Section titled “Learning Outcome Guide”At the end of this class, you should be able to…
- Attach click, change, and submit handlers through JSX.
- Use
useStateto retain a string, an array, and a boolean between renders. - Control text inputs with
valueand checkboxes withchecked. - Calculate a new array from previous state without modifying the old array.
- Explain which component owns a piece of local state.
Target behaviour
Section titled “Target behaviour”| 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 |
Remembering information between renders
Section titled “Remembering information between renders”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.
Let state describe the interface
Section titled “Let state describe the interface”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.
Activity
Section titled “Activity”Starter Kit Code
Section titled “Starter Kit Code”From the root of your workbook, grab the starter for your section. If you already have today’s starter, continue with that copy.
pnpm dlx tiged --disable-cache --force DG-InClass/SDEV-2150-A01-Sep-2026/sk/day-12/example/lesson-12-starter ./src/lesson-12pnpm dlx tiged --disable-cache --force DG-InClass/SDEV-2150-A02-Sep-2026/sk/day-12/example/lesson-12-starter ./src/lesson-12cd src/lesson-12/frontendpnpm installpnpm devOpen 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.
Code Walkthrough
Section titled “Code Walkthrough”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.
-
Give Filters a value to remember.
Import
useStateand declare the search state inside the component, before itsreturn.src/components/Filters.jsx import { useState } from 'react';import Card from './ui/Card';// src/components/Filters.jsxexport 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 <inputid="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.valuesupplies the current text. -
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. -
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.
filterand the spread syntax create new arrays. We don’t usepushorspliceon the state array.Our category contract is simple: an empty array means All. We never store the word
'All'alongside actual categories. -
Connect the category buttons.
Find the button inside the category
.map(). Replace its class and add a handler and pressed state. The starter already hastype="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-pressedalso communicates the toggle state to assistive technology.We pass a function to
onClick. WritingonClick={toggleCategory(label)}would call our handler while rendering, before the user clicks anything. -
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
valueis not its checked state; that’s why we readcheckedhere. -
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.
Check your understanding
Section titled “Check your understanding”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.
Practice
Section titled “Practice”Take this demo farther
Section titled “Take this demo farther”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, initiallynull. Pass anonClickcallback and aselectedboolean to eachResultsItem. - Update
ResultsItem.jsxto 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 theselectedprop to highlight the item and expose its pressed state. - Show the selected resource’s
titlebeneath the results list. Checksrc/data/resources.js: the property istitle, notname.
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.
Homework: Users and Posts
Section titled “Homework: Users and Posts”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.mdexplains 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.
Answered: 0 / 0 (0%)