May 16, 2021

Event handlers class vs functional components in react

In this article we are going to learn Event Handling in class component and functional component, Event handling basically is a user interaction like mouse click, mouse over, key press, change event and so on… Now lets start how to handle event in react.

First we’ll start with a class component
ClickEventClass.js
In the class based component need to access function with this keyword..

import React, { Component } from 'react';

class ClickEventClass extends Component {
    clickBtn = () => {
        alert('clicked')
    }
    render() {
        return (
            <div>
                <button onClick={this.clickBtn}>Click</button>
            </div>
        );
    }
}

export default ClickEventClass;

Now we’ll start with a functional component
FunctionalClick.js

import React from 'react';

const FunctionalClick = () => {
   const clickBtn =()=>{
        alert('Clicked')
    }
    return (
        <div>
            <button onClick={clickBtn}>Click</button>
        </div>
    );
};

export default FunctionalClick;

Note=> If we called parenthesis like this [clickBtn()]then auto called function but we need to call function on click therefore we’ll not add parenthesis.

OutPut
event-handlers-class-vs-functional-components-in-react

Leave a Reply

Your email address will not be published. Required fields are marked *