react save possibility to select text with re-render component

Tags: , ,



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:

const App = () => {
    const [someState, setSomeState] = React.useState(0);

    const clickHandler = () => {
        setSomeState(someState + 1);
    }
    return (
        <div
            className="App"
            onClick={clickHandler}
        >
            {'State ' + someState}
        </div>
    );
};

ReactDOM.render(<App />, document.getElementById("root"));

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:

const App = () => {
  const [someState, setSomeState] = React.useState(0);
  const [timeDown, setTimeDown] = React.useState(-1);

  const clickHandler = () => setSomeState(someState + 1);

  const handleMouseDown = () => setTimeDown(Date.now()); // Save the time of the mousedown event
  const handleMouseUp = () => {
    const timeUp = Date.now();
    const timeDiff = timeUp - timeDown; // Calculate the time the user took to click and hold
    if (timeDiff < 1000) { // If it's shorter than 1000ms (1s) execute the normal click handler
      clickHandler();
    } else { // Execute some other logic, or just ignore the click
      // handleLongClick();
    }
  };

  return (
    <div
      className="App"
      onMouseDown={handleMouseDown}
      onMouseUp={handleMouseUp}
    >
      {"State " + someState}
    </div>
  );
};

You can find a quick codesandbox as a demo here



Source: stackoverflow