React JS Event Handling

When user are interact applications events are fire. Application must handle this events and execute code.

We can get more idea by looking below example. you can put this file in /src/components folder and put in /src/App.js file.

Example
import React from 'react'; function ClickComponent(){ function clickHandler(){ Console.log('button is clicked'); } return ( <div> <button onClick={clickHandler}>Click Me</button> </div> ) } export default ClickComponent

In above example shows a button which have text 'Click Me'. When we click on button it will show a console log 'button is clicked'. In simple html write event in lowercase 'onclick'. But, in React we have to write in camelCase 'onClick'. In java script we call function as 'onclick=clickHandler()'. But, in React if we add () 'bracket' after function name then it is a function call. In function call case when we run code it will show console log before we clicked on button. and after clicked on button it will not call function. So, make sure not to write () in event.

Let's discuss event handler class components

Example
class ClickComponent extends Component { clickHandler() { Console.log('button is clicked'); } render() { return( <div> <button onClick={this.clickHandler}>Change Message</button> </div> ); } }

In class components only difference if this keyword while calling a function. and, no need to write function keyword.

 

← Previous

Next →