In this tutorial you will learn about the ReactJS Events and its application with practical example.
ReactJS Events
An event is an action that occurs as a result of the user action or system generated event, such as clicking mouse, pressing a key, loading of webpage, or file being created or modified etc. An event handler is a callback function which is invoked when specified event occurs. An event handler allows programmers to control the execution of the program when specified event occurs. In React, event handling is same as handling events on DOM elements, but there are following syntactic differences –
- Function is passed as event handler instead of a string.
- Events are named in camel case instead lowercase.
- In React, we must call
preventDefault
explicitly to prevent default behavior instead of returnfalse
.
Example:-
This is a simple example where we will only use one component. We are just adding onClick event that will trigger handleClick function when button is clicked, it will toggle the isToggle flag.
Step 1:- Let’s open src/App.js, delete the existing code and put the following code in it and save it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import React, { Component } from 'react'; class App extends React.Component { constructor(props) { super(props); this.state = {isToggle: true}; this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState(state => ({ isToggle: !state.isToggle })); } render() { return ( <div> <h1>W3Adda - ReactJS Events</h1> <h3>{this.state.isToggle ? 'On' : 'Off'}</h3> <button onClick={this.handleClick}> Click Me </button> </div> ); } } export default App; |
Step 2:- Let’s open the terminal again, change directory to your project folder and type the following command in order to run the server.
1 |
npm start |
Step 3:- Now open the following URL in browser to view the output
http://localhost:3000
Step 4:- You will see the following screen.