How to handle events like onClick in React?

In React, you can handle events like onClick by creating event handlers as methods within your component. Here's an example of how you can handle a click event in a React component:

  1. Define a method to handle the click event in your component class:
class Button extends React.Component { handleClick = () => { console.log('Button clicked!'); }; render() { return ( <button onClick={this.handleClick}> Click me </button> ); } }
  1. In the render method of your component, attach the handleClick method to the onClick event of the button element. This way, whenever the button is clicked, the handleClick method will be called.

  2. You can also pass additional parameters to the event handler function:

class Button extends React.Component { handleClick = (message) => { console.log(message); }; render() { return ( <button onClick={() => this.handleClick('Button clicked!')}> Click me </button> ); } }

In this example, we are passing a message 'Button clicked!' to the handleClick method when the button is clicked.

By following these steps, you can handle events like onClick in React components.