Events in React
You'll learn to run your own code when someone taps a button, with event handlers like onClick.
Watch & read
Start with the required ones. The others are there when you need them.
Explanation
You want a scorer's app: tap "Four" and the score goes up by 4. A tap is an event. The function that runs when it happens is an event handler.
In React you give the handler to the element as a prop. Event names are written in camelCase:
onClick, onChange, onSubmit.
function handleClick() {setRuns(runs + 1);}<button onClick={handleClick}>+1</button>
You pass the function. You don't call it. onClick={handleClick} means "here is the function; run
it later, when someone taps". React keeps it and calls it on each tap.
People often write onClick={handleClick()}. The () runs the function right now, while React is
drawing the screen, and gives onClick its result instead. If that function sets state, React renders
again, runs it again, and stops with a "Too many re-renders" error.
When the handler needs a value, wrap it in a small arrow function:
<button onClick={() => addRuns(4)}>Four</button>
Now the arrow is what React keeps. On a tap, the arrow runs, and it calls addRuns(4).
When you read JSX, check every on...={ }. Is there a function name or an arrow inside? Good. Is there
a call with () and no arrow? That runs too early.
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1function Wallet() {2 const [balance, setBalance] = useState(500);34 return (5 <div>6 <p>{balance} Tk</p>7 <button onClick={setBalance(balance - 100)}>Send 100</button>8 </div>9 );10}
Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3When does
handleClickrun in<button onClick={handleClick}>? - 2 / 3How do you run
addRuns(6)when a button is tapped? - 3 / 3How is the click event written in JSX?
Explain it back
How confident are you with Events in React?
Done
onClick={...} and say when the code runs, and spot a handler that runs too early.