- ReactJS support event handling using SyntheticEvents.
- These synthetic events are wrapper around Browser event.This wrapper provides cross browser supports.
- In this demo, “We will learn to use synthetic event in a ReactJS component”.
- The following code contains MyButtonComponent in ReactJS.In its render method a button is assigned with a click synthetic event using onClick. This code is saved in my mybutton-component.js file.
import React from 'react'; class MyButtonComponent extends React.Component { sayHello(){ console.log("Hello "+ this.props.message); alert("Hello "+ this.props.message) } render() { console.log(this.props) return <button onClick={this.sayHello.bind(this)}>Click Me</button>; } } export default MyButtonComponent;
- This click event calls the sayHello() method which is glued with bind() method with this parameter.As we can see sayHello() method is public member function of MyButtonComponent class and is accessible by the instances of MyButtonComponent.React automatically binds all the methods inside a component to this.
- In this.sayHello.bind(this) has 2 this. The 1st this refers the the button and 2nd this refers to MyButtonComponent instance.
- The following code imports the MyButtonComponent and renders it to a DOM element.
import React from 'react'; import ReactDOM from 'react-dom'; import MyButtonComponent from './mybutton-component'; ReactDOM.render( <MyButtonComponent message="Developers"/>, document.getElementById("component-container") );
- The following screenshot shows the output of this example:-