Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Use Plain JavaScript Events in React

Nov 18, 2020 • 4 Minute Read

Introduction

React supports events that are supported in JavaScript, and it works similarly, but the significant difference is its way of using the events. There are two significant differences:

  • To use JavaScript events in React, you need to name it in camel case such as eventName().
  • If you use JSX with React, then you need to pass the event as a string with the event handler.

JavaScript events are used to perform various operations based on events such as click, touch, up, and down. All the events, called synthetic events, can be used in React. This guide will demonstrate how to use plain JavaScript events within React components.

Event Listener and the Event Function

Unlike JavaScript, React does not allow you to use event names as you do with JavaScript, like onclick(); hence you need to follow the event name as onClick().

You can still use plain JavaScript events using the window object used to represent the DOM document opened in the current browser window.

Implementing JavaScript click Event

A click event is the most common event used to trigger a function based on the click event on the elements such as button, label, span, link, etc. To add the click event in React using plain JavaScript, you need to use addEventListener() to assign the click event to an element.

Create one <button> element as ref props so that it can be accessed to trigger the click event.

      render() {
    return (
      <>
        <button ref={mybutton => (this.btn = mybutton)}>Click me</button>
      </>
    );
}
    

The <button> element has additional props called ref that are used to find the element from the DOM. To assign the JavaScript click event handler, you can implement it as demonstrated below.

      componentDidMount() {
    this.btn.addEventListener("click", this.onButtonClick);
}
    

addEventListener() assigns the event handler and the event name to do an activity once the button gets clicked.

      onButtonClick() {
    alert("Clicked on Button");
}
    

Once you click the button, it will show the alert box that the click event is triggered.

Implementing JavaScript change Event

The change event triggers the event based on the existing value and processes changes based on the changed value. Using the addEventListener(), you can assign change as the event handler followed by the event handler function as given below.

      componentDidMount() {
    this.input.addEventListener("change", e => this.onChange(e));
}
    

Then, you can implement the event handler function to process the updated values.

      onChange(e) {
    console.log("Updated values is :-", e.target.value);
}
    

Alternatively, you can remove the listener using document.getElementByID() along with the addEventListener() as given below.

      document.getElementById("#your_id").addEventListener("change", this.onChange);
    

Remove the Event Listener and Assigned Event Function

So far, this guide has shown how to define the JavaScript event handler and associated event handler function. But you should remove the listener once the current component gets unmounted from the DOM.

To remove the event listener, you can use removeEventListener() along with the event type and the event handler function.

      componentWillUnmount() {
    this.btn.removeEventListener("click", this.onButtonClick);
    this.input.removeEventListener("change", e => this.onChange(e));
}
    

As you can see in the above code, the componentWillUnmount() function is implemented for anything that needs to get removed, such as promises and events.

Inside the function, two events removed are from the DOM, click and change, followed by the event handler function, so you can use the removeEventListener() to remove the attached events from the component.

Alternatively, you can remove the listener using document.getElementByID() along with removeEventListener().

      document.getElementById("#your_id").removeEventListener("change", this.onChange);
    

Conclusion

React supports most of the JavaScript events but with a different version of the naming convention; hence, you should only use the React-based naming convention and not the plain JavaScript events with the React elements.

Events handle the element's response based on actions such as click, touch, drag, up, down, etc. To perform specific events, you can use various React synthetic events to trigger any actions.

Gaurav Singhal

Gaurav S.

Guarav is a Data Scientist with a strong background in computer science and mathematics. He has extensive research experience in data structures, statistical data analysis, and mathematical modeling. With a solid background in Web development he works with Python, JAVA, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React. His data science skills include Python, Matplotlib, Tensorflows, Pandas, Numpy, Keras, CNN, ANN, NLP, Recommenders, Predictive analysis. He has built systems that have used both basic machine learning algorithms and complex deep neural network. He has worked in many data science projects, some of them are product recommendation, user sentiments, twitter bots, information retrieval, predictive analysis, data mining, image segmentation, SVMs, RandomForest etc.

More about this author