As in functional component event handling class too support multiple approach for event handling. In our example we have four buttons( class components ) which respond to the button click.
Our App.js have the following code
import Button1 from "./components/Button1"; import Button2 from "./components/Button2"; import Button3 from "./components/Button3"; import Button4 from "./components/Button4"; import "./App.css" function App() { return <div className="App"> <Button1/> <Button2/> <Button3/> <Button4/> </div> } export default App;
In class component in , we can add event handler using any of the following method.
-
Binding event handler in render method
-
Bind event handler in class contractor
-
Event handler as class property
-
An arrow function in the render method
Binding event handler
The first two method, we have to bind the event handler using the this operator. For this create a function for handle particular event then we can bind the function in the constructor/render and pass it to the corresponding event as follows.
import React, { Component } from 'react' class Button3 extends Component { constructor(props) { super(props) this.handleClick=this.handleClick.bind(this) } handleClick () { alert('Button3 Clicked') } render() { return ( <div> <button onClick={this.handleClick}>Button3 - Binding in constructor</button> </div> ) } } export default Button3
In the second approach we can move the binding to the render. Function call at render time may cause performance cut, in bigger applications.
import React, { Component } from 'react' class Button3 extends Component { handleClick () { alert('Button3 Clicked') } render() { return ( <div> {/* binding @ render*/} <button onClick={this.handleClick.bind(this)}>Button3 - Binding in render</button> </div> ) } } export default Button3
Arrow function as event handler
We can use an arrow function as property of the class to handle the event as follows
import React, { Component } from "react"; class Button2 extends Component { handleClick = () => { alert("Button2 Clicked"); }; render() { return ( <div> {/* Arrow function- as class property */} <button onClick={this.handleClick}>Button2 - Arrow Fun - class property</button> </div> ); } } export default Button2;
Arrow function at render method
We can also use the arrow function in the render method as follows
import React, { Component } from 'react' class Button1 extends Component { render() { return ( <div> {/* Arrow function in render */} <button onClick={()=> alert('Button1 clicked')}>Button1 - Arrow Fun in render</button> </div> ) } } export default Button1
Which method is right ?
While all the methods are ok in normal case, while dealing with big data render methods may cause performance cut. React official document suggest either class property ( using arrow function) or binding at constructor.
The complete set of example in this tutorial can be found @