1. How React Events Work 🖱️
Handling events in React is very similar to handling events on regular HTML DOM elements, but with a few important syntax differences:
- React event names are written in camelCase (e.g., `onclick` becomes `onClick`).
- You pass a function as the event handler, rather than a string.
For example, in plain HTML, you might do this:
<button onclick="handleClick()">Click Me</button>
In React, it looks like this:
<button onClick={handleClick}>Click Me</button>
Notice we are passing the `handleClick` function itself inside curly braces `{}`. We are not calling it with `()`. The function will be executed by React only when the button is clicked.
2. Defining an Event Handler Function
An event handler is just a function that you define inside your component. This function will be called whenever the specified event occurs.
Let's create a simple `AlertButton` component. When you click the button, it will show a JavaScript alert.
function AlertButton() {
// 1. Define the function that will run on click
const handleButtonClick = () => {
alert('You clicked the button!');
};
return (
// 2. Pass that function to the onClick prop of the button
<button onClick={handleButtonClick}>
Click for an alert
</button>
);
}
// Render the component
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<AlertButton />);
3. Using Inline Functions for Simple Events
For very simple actions, it can be convenient to define the event handler function directly inside the JSX. This is called an "inline function" or a "lambda function".
This is useful when your logic is short and you don't need to reuse it elsewhere.
function ConsoleLogger() {
return (
<button onClick={() => console.log('Button was clicked!')}>
Log to Console
</button>
);
}