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:
import React from 'react'; function MyComponent() { // This is called when the button is pressed const buttonPressed = () => { alert('Button pressed'); } return ( <div> <button onClick={buttonPressed}>Press Me</button> </div> ); }; export default MyComponent;
In React, you cannot return false
from the event handler to prevent the default behavior. Instead, you should call the preventDefault()
method. In the following example, we are using a form
element, and...