23. Events
Reacting to the User
Web applications are interactive. Users click buttons, type in search bars, and submit forms. In standard JavaScript, you use addEventListener. In React, we attach event handlers directly to the JSX elements using camelCase props.
Attaching Event Handlers
React events are written in camelCase (onClick, onChange, onSubmit). You pass a function reference to the event handler, not a string.
The Crucial Mistake: Passing vs Executing
A very common beginner mistake is writing onClick={handleClick()}. Notice the parentheses. This tells JavaScript to execute the function immediately when the component renders, instead of waiting for the user to click. You must pass the function reference (no parentheses) or wrap it in an arrow function.
The Event Object (e)
When an event fires, React automatically passes an "Event Object" to your handler function. This object contains massive amounts of useful data, like what the user just typed into a text input.
Preventing Default Behavior
Some HTML elements have default behaviors. For example, submitting an HTML <form> will automatically refresh the entire browser page. In a React Single Page Application, a page refresh destroys all your state! You must stop it.
Knowledge Check
Ready to test your understanding of 23. Events?