EN
React - press and hold mouse button example
0 points
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,onMouseUp
/onMouseLeave
events - to stop incrementing the counter,useEffect
hook - to stop the counter when App component is destroyed.
Runnable example:
xxxxxxxxxx
1
// Note: Uncomment import lines while working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => {
6
const [counter, setCounter] = React.useState(0);
7
const intervalRef = React.useRef(null);
8
9
React.useEffect(()=> {
10
return () => stopCounter(); // when App is unmounted we should stop counter
11
}, []);
12
13
const startCounter = () => {
14
if (intervalRef.current) return;
15
intervalRef.current = setInterval(() => {
16
setCounter((prevCounter) => prevCounter + 1);
17
}, 100);
18
};
19
20
const stopCounter = () => {
21
if (intervalRef.current) {
22
clearInterval(intervalRef.current);
23
intervalRef.current = null;
24
}
25
};
26
27
return (
28
<div>
29
<h2>{counter}</h2>
30
<div>
31
<button
32
onMouseDown={startCounter}
33
onMouseUp={stopCounter}
34
onMouseLeave={stopCounter}>
35
Press and hold to increment.
36
</button>
37
</div>
38
</div>
39
);
40
};
41
42
const root = document.querySelector('#root');
43
ReactDOM.render(<App />, root );