ReactQuestion 22 of 28
Task: search on button click
Answer out loud or in your head first, then compare.
Answer
I keep the typed text separate from the submitted query. That way the filter changes when the form is submitted, not on every keystroke.
JSX
import { useState } from 'react';
const items = ['React', 'Node', 'JavaScript'];
export default function Search() {
const [input, setInput] = useState('');
const [query, setQuery] = useState('');
const results = items.filter(item =>
item.toLowerCase().includes(query.toLowerCase())
);
return <>
<form onSubmit={e => { e.preventDefault(); setQuery(input.trim()); }}>
<label>Search <input value={input} onChange={e => setInput(e.target.value)} /></label>
<button type="submit">Search</button>
</form>
<ul>{results.map(item => <li key={item}>{item}</li>)}</ul>
{!results.length && <p>No results</p>}
</>;
}Pitfall: filtering directly on the input's state wouldn't meet the requirement to search only when the button is pressed.
How did it go? Be honest — “Not yet” puts the question on your review list.
Practise in code
- Search on button click — guided self-review