onMouseDown and onMouseUp Event handling in ReactJs

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