In React class-based components when we use event handler callbacks, it is very important to give special attention to the ‘this’ keyword. In these cases the context this is undefined when the callback function actually gets invoked that’s why we have to bind the context of this. Now if binding all the methods of each class is very annoying. Instead of binding we can use the inline arrow function since the arrow function does not have its own value of this, it uses the parent or public value. Using the inline arrow function we can get rid of annoying method binding every time and also the code looks very packed and organized.
Example 1: This example illustrates how to use arrow functions in callbacks
-
index.js:
Javascript
import React from'react'import ReactDOM from'react-dom'import App from'./App'ReactDOM.render(<App />, document.querySelector('#root'))chevron_rightfilter_none -
App.js :
Javascript
import React, { Component } from'react'class App extends Component {// Default propsstatic defaultProps = {courceContent : ['JSX','React Props','React State','React Lifecycle Methods','React Event Handlers','React Router','React Hooks','Readux','React Context']}constructor(props){super(props)// Set initial statethis.state = {msg :'React Cource', content:''}}// Return an unordered list of contentsrenderContent(){return(<ul>{/* map over all the contents andreturn some JSX for each */}{this.props.courceContent.map(content => (<li>{content}</li>))}</ul>)}render(){const button = !this.state.content &&<button// Arrow function in callbackonClick={() => {// Update statethis.setState({msg :'Cource Content',content :this.renderContent()})}}>Click here to know contents!</button>return(<div><p>{this.state.msg}</p><p>{this.state.content}</p>{button}</div>)}}exportdefaultAppchevron_rightfilter_none
Output :

Example 2 :
-
index.js :
Javascript
import React from'react'import ReactDOM from'react-dom'import App from'./App'ReactDOM.render(<App />, document.querySelector('#root'))chevron_rightfilter_none -
App.js :
Javascript
import React, { Component } from'react'class App extends Component{// Default propsstatic defaultProps = {name : ['John','Alex','Bob']}constructor(props){super(props)// Nnitialize count statethis.state = {msg :'Hi There', count:0}}render(){return(<div><h3>Greetings!</h3><p>{this.state.msg}</p><button// Arrow function in callback// does not required explicit bindingonClick={() => {this.setState(st => (st.msg = `${st.msg}, ${this.props.name[st.count]}`,st.count += 1))}}>Say greeting to employees!</button></div>)}}exportdefaultAppchevron_rightfilter_none
Output :



