When an input
element is disabled, it won’t be handled by any event.
<input disabled />
How to achieve that for any element (e.g. a span
element)?
I’ve tried using pointer-events: "none"
but it only prevents click events. Other event such as onKeyDown
can still be called.
Here is an example :
import * as React from "react";
export default function UnstyledSwitches() {
return (
<div>
<span tabIndex={0} onKeyDown={() => console.log("clicked")}>
test
</span>
</div>
);
}
https://codesandbox.io/s/base-cra-typescript-forked-43708i?file=/src/App.tsx
Focus on the span with tab and then click spacebar. The function that is supplied to onKeyDown
props will be called. I want the function to not be called.
2
Answers
One solution can be to add the
disabled
attribute to the element and then use javascript to limiteventListeners
to not-disabled elements.For example:
In html:
In js:
But, if elements are being disabled/enabled dynamically, you’d need to add eventListeners after each change in element’s state.
pointerEvents and tabIndex
The question asks how to prevent keyboard input on a span. However, the code included in the question assigns a value to the element’s tabIndex. Setting the tabIndex (or contentEditable) attribute allows the element to receive focus along with keyboard events.
Removing the tabIndex from the span prevents focus and keyboard events, but not mouse events. To prevent both keyboard and mouse events, set pointerEvents to "none". The tabIndex setting doesn’t appear to make any difference with a span, but might with an input.
OP notes that pointerEvents "none" did not work and yet in the snippet it does. The reason is unclear, but perhaps it due to different testing methods.
React Snippet
The snippet contains a few span elements with different configurations to try.