Languages
[Edit]
EN

React - press and hold mouse button example

0 points
Created by:
Kadeem-Craig
516

In this article, we would like to show you mouse button press and hold example in React.

There is no press and hold mouse button event in React. However, we wanted to show you how to perform some logic when the mouse button is pressed and held, and how to break this logic when we stop pressing the button or when our cursor leaves the button field.

Below example presents how to create a counter which increments on button press and hold every 0.1s.

In the example we use:

  • useState hook - to manage the counter as App component's state,
  • useRef hook - to create a reference that will help us to set and clear the interval,
  • onMouseDown event - to start incrementing our counter,
  • onMouseUponMouseLeave events  - to stop incrementing the counter,
  • useEffect hook - to stop the counter when App component is destroyed.

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const App = () => {
    const [counter, setCounter] = React.useState(0);
    const intervalRef = React.useRef(null);

    React.useEffect(()=> {
      	return () => stopCounter(); // when App is unmounted we should stop counter
    }, []);

    const startCounter = () => {
        if (intervalRef.current) return;
        intervalRef.current = setInterval(() => {
          	setCounter((prevCounter) => prevCounter + 1);
        }, 100);
    };

    const stopCounter = () => {
        if (intervalRef.current) {
            clearInterval(intervalRef.current);
            intervalRef.current = null;
        }
    };

    return (
      <div>
        <h2>{counter}</h2>
        <div>
          <button
            onMouseDown={startCounter}
            onMouseUp={stopCounter}
            onMouseLeave={stopCounter}>
            Press and hold to increment.
          </button>
        </div>
      </div>
    );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

Alternative titles

  1. React - mouse click and hold example
  2. React - increment counter on mouse button press and hold
  3. React - press and hold mouse button with setInterval example
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join