Handling events with React
Event handling in React is similar to handling DOM element events. The difference compared to HTML event handling is that event naming uses camelCase in React. The following sample component code adds an event listener to a button and shows an alert message when the button is pressed:
function MyComponent() {
// This is called when the button is pressed
const handleClick = () => {
alert('Button pressed');
}
return (
<>
<button onClick={handleClick}>Press Me</button>
</>
);
};
export default MyComponent;
As we learned earlier in the counter example, you have to pass a function to the event handler instead of calling it. Now, the handleClick
function is defined outside the return
statement, and we can refer to it using the function name:
// Correct
<button onClick={handleClick}>Press Me</button>
// Wrong
<button onClick={handleClick()}>Press Me</button>
...