Abhinav Kinagi
Abhinav Kinagi

Reputation: 3821

How to fire onSelectStart in React/JSX?

I'm familiar with the usage of selectstart event in HTML. I'm using onSelectStart in JSX. I expect it connects to onselectstart. But, it throws a warning saying that it's unknown.

Warning: Unknown event handler property `onSelectStart`. It will be ignored.

Example code:

function Example() {
  return (
    <div className="Example">
      <h2 onSelectStart={() => console.log("Selection started")}>Click</h2>
    </div>
  );
}

I've tried this with react/[email protected] and [email protected].

Edit loving-proskuriakova-ute7j

Is there an alternative for onSelectStart? If yes, how to implement the same?

Upvotes: 0

Views: 2676

Answers (1)

Rikin
Rikin

Reputation: 5473

Apparently https://reactjs.org/docs/events.html#selection-events not supported by react it seems. Even on MDN docs this dont seem to be standardized event: https://developer.mozilla.org/en-US/docs/Web/API/Document/selectstart_event#Specifications so I would question validity of its usage.

Here's the workaround using refs:

https://codesandbox.io/s/fancy-wave-sotun

    ref={el => {
      el &&
        el.addEventListener("selectstart", () => {
          console.log("Selection started");
        });
    }}

Just dont forget to remove Event listener on unmount of component.

Upvotes: 3

Related Questions