Event Handling in ReactJS

Any actions triggered at which JavaScript can respond is called Events.

Some JavaScript events:

  • Clicking an element
  • Submitting a form
  • Scrolling a page
  • On hovering an element
  • Mouse out from an element

Event Handling in ReactJS is very similar to handling events on DOM elements. There are only syntactic differnce.

  • React events are named using camelCase.
  • Using JSX, you pass a function as the event handler, rather than a string.

Let us understand with an example –

In HTML:

<button onclick=”funcClick()”> Click Here </button>

In React:

//Function Component...
<button onClick="{funcClick}> Click Here </button>

//Class Component...
<button onClick="{this.funcClick}> Click Here </button>

Here, incase of React, you should not have to use function bracket “()” in onClick function name.

Event Handling directly in class component

Let us understand by an example

import React, { Component } from "react";

class Tutorial extends Component{

    clickEvent = () => {
        console.log("Button Cliecked!", this);
    }

    render(){
        return(
            <div>
                <h1>Learn Event Handling in ReactjS</h1>
                <button onClick={this.clickEvent}>Click Here</button>
            </div>
        );
    }
}

export default Tutorial;

index.js

import React from "react";
import ReactDOM from "react-dom";

import Tutorial from './Tutorial';

//Rendering component...
ReactDOM.render(<Tutorial />, document.getElementById("root"));

Event Handling inside class constructor

Tutorial.js

import React, { Component } from "react";

class Tutorial extends Component{

    constructor(props){
        super(props);
        this.clickEvent = this.clickEvent.bind(this);
    }

    clickEvent(){
        console.log("Button Cliecked!", this);
    }

    render(){
        return(
            <div>
                <h1>Learn Event Handling in ReactjS</h1>
                <button onClick={this.clickEvent}>Click Here</button>
            </div>
        );
    }
}

export default Tutorial;

index.js

import React from "react";
import ReactDOM from "react-dom";

import Tutorial from './Tutorial';

//Rendering component...
ReactDOM.render(<Tutorial />, document.getElementById("root"));

You cannot return false to prevent default behavior in ReactJS. you must call preventDefault explicitly.

For example

In HTML

<a href="#" onclick="console.log('clicked'); return false" > Click Here </a>

In ReactJS

function clickEvent(e){
	e.preventDefault();
	console.log('Clicked');
}

<a href="#" onClick={clickEvent}> Click Here </a>

Trending Topics