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


import React, { Component } from 'react';
class App extends Component {
  constructor(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 className="h4 bg-secondary text-white text-center p-2">
          { this.state.message }
        <div className="text-center">
          <button className="btn btn-secondary" onMouseDown={ this.handleEvent } onMouseUp={ this.handleEvent } >
           Change Image
export default App;
Most Helpful This Week