When user press the mouse button down, a mousedown event is triggered, and when user release, a mouseup event is triggered. The handleEvent method uses the type property to determine which event is being handled and updates the message value accordingly.
Create React App
Type the following command to create a new react app:
npx create-react-app demo
Now, go to the project folder:
cd demo
Now, update default App.js with below code snippet
src\App.js
import React, { Component } from 'react'; class App extends Component { constructor(props) { super(props); this.state = { message: "Mouse Event" } } handleEvent = (event) => { if (event.type === "mousedown") { this.setState({ message: "Mouse Down"}); } else { this.setState({ message: "Mouse Up"}); } } render() { return ( <div> <div className="h4 bg-secondary text-white text-center p-2"> { this.state.message } </div> <div className="text-center"> <button className="btn btn-secondary" onMouseDown={ this.handleEvent } onMouseUp={ this.handleEvent } > Change Image </button> </div> </div> ); } } export default App;
Most Helpful This Week
Display JSON Data in React JS
React JS onClick event handler
How to use arrow function in React stateless components?
How to render raw HTML content in React JS?
Loop inside React JSX
React JS Count number of checkboxes are checked
How to set property values using expression?
onClick Event binding and get event name in ReactJs
How to use createElement in React JS?
3 Different Examples - How State Works in React?