React JS Tutorial - DOM Events
In this tutorial, we will learn about DOM events in React. All React events are written in camelCase, and event handlers are written inside curly braces.
Let's see how we can use DOM events in our React application. Go to your project and open the Post Component.
Inside the Post Component, let's add a button as follows:
<button onClick={} >Click Here</button>
Next, we need to create a click handler method. Inside the curly braces, add the click handler method. First, create the method as follows:
handleClick(e){
console.log(this.state);
}
Now, add this handleClick method inside the curly bracket:
<button onClick={this.handleClick} >Click Here</button>
Let's see the result. Go to your browser, and you should see the button. Make the console visible by right-clicking and choosing "Inspect Element". Then, click on the "Console" tab.
Now, click on the button, and you should see the state elements displayed in the console.
onMouseOver Event
Next, let's see the onMouseOver event in action. Create another button as follows:
<button onMouseOver={} >Mouse Hover Here</button>
Now, create a function to handle the mouse over event:
handleMouseOver(e)
{
console.log(e.target,e.pageX)
}
Add this method to the button:
<button onMouseOver={this.handleMouseOver} >Mouse Hover Here</button>
Let's check it. Switch to your browser, and hover over the button. You should see the x value displayed in the console.
onCopy Event
Finally, let's see the onCopy event in action. Create a paragraph as follows:
<p onCopy={} >This is a test paragraph</p>
Now, create a method to handle the copy event:
handleCopy(e){
console.log('Paragraph has been copied!');
}
Let's check it. Switch to your browser, and try to copy the paragraph. You should see the message "Paragraph has been copied" displayed in the console.
That's it! You have successfully learned how to use DOM events in React. By following these steps, you can handle various events in your React application.