Which methods would you use to handle events in React?

Experience Level: Junior
Tags: React

Answer

In React, there are several methods that can be used to handle events. One of the most commonly used methods is onClick. This method is used to handle click events on a particular element. For example, if you have a button on your page and you want to perform some action when the user clicks on it, you can use the onClick method to handle the click event. Here is an example of how you can use the onClick method in React:


function handleClick() {
  console.log('Button clicked');
}

function App() {
  return (
    <button onClick={handleClick}>Click me</button>
  );
}

Another method that can be used to handle events in React is onChange. This method is used to handle changes to form elements such as input fields, select boxes, and text areas. For example, if you have a form on your page and you want to perform some action when the user types something into an input field, you can use the onChange method to handle the change event. Here is an example of how you can use the onChange method in React:


function handleChange(event) {
  console.log('Input changed: ' + event.target.value);
}

function App() {
  return (
    <input type="text" onChange={handleChange} />
  );
}

Finally, there is also the onSubmit method, which is used to handle form submissions. This method is typically used in conjunction with the <form> element. When the user submits the form, the onSubmit method is called, and you can perform some action based on the form data. Here is an example of how you can use the onSubmit method in React:


function handleSubmit(event) {
  event.preventDefault();
  console.log('Form submitted');
}

function App() {
  return (
    <form onSubmit={handleSubmit}>
      <input type="text" />
      <button type="submit">Submit</button>
    </form>
  );
}
React for beginners
React for beginners

Are you learning React ? Try our test we designed to help you progress faster.

Test yourself