Handling events lets your React app respond when users click buttons, type in inputs, or do other actions. It makes your app interactive and fun to use.
Handling events in React
function MyComponent() { function handleClick(event) { // code to run on click } return ( <button onClick={handleClick}>Click me</button> ); }
Use camelCase for event names like onClick, onChange.
Pass a function to the event attribute, not a string.
function MyButton() { function sayHello() { alert('Hello!'); } return <button onClick={sayHello}>Say Hello</button>; }
function InputLogger() { function logInput(event) { console.log(event.target.value); } return <input type="text" onChange={logInput} />; }
function InlineHandler() { return <button onClick={() => alert('Clicked!')}>Click me</button>; }
This component shows a button and a count. Each time you click the button, the count increases by one and updates on the screen.
It uses useState to keep track of clicks and onClick to handle the button press.
Also includes an aria-label for accessibility.
import React, { useState } from 'react'; function ClickCounter() { const [count, setCount] = useState(0); function handleClick() { setCount(prevCount => prevCount + 1); } return ( <div> <button onClick={handleClick} aria-label="Increment count">Click me</button> <p>You clicked {count} times</p> </div> ); } export default ClickCounter;
Always use camelCase event names in React, like onClick, not lowercase.
Pass a function reference or an inline function, not a string like in HTML.
Remember to use accessibility attributes like aria-label for better user experience.
React uses camelCase event names and functions to handle events.
Event handlers let your app respond to user actions like clicks and typing.
Use useState to update your UI when events happen.
Practice
Solution
Step 1: Understand React event naming
React uses camelCase for event handlers, soonClickis correct, not lowercase or capitalized differently.Step 2: Attach event handler as a function reference
In React, event handlers are passed as functions, not strings. So{handleClick}is correct, not a string like "handleClick()".Final Answer:
<button onClick={handleClick}>Click me</button> -> Option BQuick Check:
React event handler syntax =<button onClick={handleClick}>Click me</button>[OK]
- Using lowercase event names like onclick
- Passing event handler as a string instead of function
- Capitalizing event names incorrectly
Solution
Step 1: Recognize JavaScript function syntax in React
React functional components use JavaScript, preferring arrow functions declared withconstfor event handlers.Step 2: Identify correct arrow function syntax
const handleClick = () => console.log('Clicked');is correct. Other options have syntax errors such as missing variable declaration or invalid syntax.Final Answer:
const handleClick = () => console.log('Clicked'); -> Option AQuick Check:
Arrow function syntax = const handleClick = () => console.log('Clicked'); [OK]
- Using invalid function syntax like 'handleClick() => {}'
- Using Python syntax 'def' in JavaScript
- Not assigning function to a variable
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const handleClick = () => setCount(count + 1);
return (
<button onClick={handleClick}>Clicked {count} times</button>
);
}Solution
Step 1: Understand useState initial value
The state variablecountstarts at 0, so the button initially shows 'Clicked 0 times'.Step 2: Analyze handleClick behavior
Each click callshandleClick, which updatescountby adding 1, so the displayed count increments on each click.Final Answer:
Button shows 'Clicked 0 times' initially and increments on each click -> Option AQuick Check:
useState increments count on click = Button shows 'Clicked 0 times' initially and increments on each click [OK]
- Thinking state does not update on click
- Confusing initial state with updated state
- Expecting runtime errors from correct code
function MyButton() {
const handleClick = () => {
console.log('Clicked');
}
return <button onclick={handleClick}>Click me</button>;
}Solution
Step 1: Check event handler attribute name
React requires camelCase event names, soonclickis incorrect; it should beonClick.Step 2: Verify function definition and usage
The functionhandleClickis correctly defined and passed as a reference, so no error there.Final Answer:
Incorrect event name 'onclick' should be 'onClick' -> Option CQuick Check:
React event names are camelCase = Incorrect event name 'onclick' should be 'onClick' [OK]
- Using lowercase event names
- Forgetting to pass function reference
- Misunderstanding JSX syntax for elements
function EnterCounter() {
const [count, setCount] = React.useState(0);
const handleKeyDown = (event) => {
// What condition should be here?
};
return (
<>
<input type="text" onKeyDown={handleKeyDown} aria-label="Enter key counter input" />
<p>Count: {count}</p>
</>
);
}Solution
Step 1: Identify the correct property for key detection
Modern React and browsers useevent.keyas a string to detect keys, so checkingevent.key === 'Enter'is correct.Step 2: Understand deprecated properties
event.keyCodeandevent.whichare deprecated or inconsistent; also, comparingevent.keyto a number like 13 is incorrect.Final Answer:
if (event.key === 'Enter') setCount(count + 1); -> Option DQuick Check:
Use event.key string for key detection = if (event.key === 'Enter') setCount(count + 1); [OK]
- Using deprecated event.keyCode or event.which
- Comparing event.key to a number instead of string
- Not checking key inside keydown event
Ready to prove it?
Pass the test and this pattern moves unknown
