i have component with text. It changed component own state with mouse click. But i want to save possibility to select and copy in by long click. Is there way to make it ? Selection is reset after rerender component. Code for example:
JavaScript
x
19
19
1
const App = () => {
2
const [someState, setSomeState] = React.useState(0);
3
4
const clickHandler = () => {
5
setSomeState(someState + 1);
6
}
7
return (
8
<div
9
className="App"
10
onClick={clickHandler}
11
>
12
{'State ' + someState}
13
</div>
14
);
15
};
16
17
ReactDOM.render(<App />, document.getElementById("root"));
18
19
Advertisement
Answer
How about using onMouseDown
and onMouseUp
events yourself and calculate the time the user took to click instead of using onClick
?
You could for example do something like this:
JavaScript
1
28
28
1
const App = () => {
2
const [someState, setSomeState] = React.useState(0);
3
const [timeDown, setTimeDown] = React.useState(-1);
4
5
const clickHandler = () => setSomeState(someState + 1);
6
7
const handleMouseDown = () => setTimeDown(Date.now()); // Save the time of the mousedown event
8
const handleMouseUp = () => {
9
const timeUp = Date.now();
10
const timeDiff = timeUp - timeDown; // Calculate the time the user took to click and hold
11
if (timeDiff < 1000) { // If it's shorter than 1000ms (1s) execute the normal click handler
12
clickHandler();
13
} else { // Execute some other logic, or just ignore the click
14
// handleLongClick();
15
}
16
};
17
18
return (
19
<div
20
className="App"
21
onMouseDown={handleMouseDown}
22
onMouseUp={handleMouseUp}
23
>
24
{"State " + someState}
25
</div>
26
);
27
};
28
You can find a quick codesandbox as a demo here