Proper use of events with reactjs – ES6

What is an event ?.  Event are used when JavaScript want to interact with HTML. For example when page loads, it's called event. When user click on button, Moving a mouse pointer over a div component all those are events. If we want to do some or to give response to user when an event occur, we use JavaScript for that.

Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events which can trigger JavaScript Code. Events are represented as objects and may have additional custom fields and/or functions used to get additional information about what happened. Events can represent everything from basic user interactions to automated notifications of things happening in the rendering model.

Events are categorized based on their function, property, usage and etc. So you may have seen different type of event categories. In here our main focus is to deal with events. Some events can be easily handle inside reactjs using ES6 syntax, but some may not. For example "onClick", "onChange" events can be handle easily. Some events like "onScroll" event trigger in document level on scrolling a "Div".

If you want to catch scrolling your webpage and do some stuff, how to do that. It is so simple than you think. First of all add window event listener to "componentDidMount" function.

componentDidMount(){
    window.addEventListener('scroll', this.handleScroll);
  }

Above you can see that we are passing "scroll" event to "handleScroll" function. Using that function let's add popup when user scroll your webpage.

handleScroll = (e) => {
    var posY = parseInt(e.currentTarget.scrollY);
    if(posY > 105){
      alert("Do something here")
    }
  }

Still not over. You just add an window level event listener. What happen when you load another reactjs component. Even though your page scrolling component is not viewing it keep logging errors on console. You have to remove that event listener when "componentWillUnmount".

  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
  }

That's all. Using above method you can use DOM events inside ES6 classes with Reactjs. Please leave a comment to support me. If you have any issue when using events please leave a comment.

Add a Comment

You have to agree to the comment policy.