Intermediate
How do you handle events in React?
Event handling in React is a key aspect of building interactive applications. React provides a synthetic event system that wraps the native events to ensure consistent behavior across different browsers.
Here’s how to handle events:
- Define the Event Handler: Create a function that will handle the event.
- Attach the Handler: Use JSX syntax to attach the event handler to an element.
- Bind 'this': If using class components, bind the handler to ensure correct context.
Example:
class MyButton extends React.Component { handleClick() { alert('Button clicked!'); } render() { return <button onClick={this.handleClick.bind(this)}>Click Me</button>; } }