Current Answer
TLDR for this answer is that after providing 2 attempts at this answer I've tried to do further research but I cannot find a working answer (myself). It looks like perhaps because <select>
uses the native dropdown it's not possible to prevent this action? Hopefully, someone can correct me if I am incorrect. In truth to respond to this question, I would recommend building your own custom dropdown component in React as this will give you an opportunity to experiment with fundamentals in React anyways and gives you full control of your component.
I made a codepen of two examples where I was grabbing the key events on a Select component but to be honest, the event capturing was iffy at best and as I said above I think the interference of the native components (like the dropdown) from the browser will prevent you from altering any functionality here.
Other Answers
Answer partly taken from here: How to detect escape key press with pure JS or jQuery?
You'll need to capture the escape key by using an if statement to detect if that particular key was pressed onKeyDown and preventing the default behavior of that key using the event you're passing in.
Answer 1:
<select
onChange = {(e) => console.log("in change")}
onKeyDown = {(e) => {
if(e.key === "Escape") {
e.preventDefault();
}
}
name="pets" id="pet-select"
>
<option value="">--Please choose an option--</option>
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="hamster">Hamster</option>
<option value="parrot">Parrot</option>
<option value="spider">Spider</option>
<option value="goldfish">Goldfish</option>
</select>
Edit: Other Tips (I fixed in the code above):
When you're only returning a console log you don't have to wrap it with {} you can just plainly return the console log on its own. You also had some syntax errors in that piece of code you posted for the console.log that I cleaned up.
Answer 2:
This answer is using React's hooks where we are creating a reference to the select element with our useRef hook. We then take that current reference and add an event listener for keydown (and prevent escape).
const Element = () => {
const selectRef = React.useRef(null);
React.useEffect(() => {
if (selectRef.current) {
selectRef.current.addEventListener("keydown", handleOnKeyDown);
}
return () => {
selectRef.current.removeEventListener("keydown", handleOnKeyDown);
};
}, [selectRef, selectRef.current]);
const handleOnKeyDown = (e) => {
if (e.key === "Escape") {
e.preventDefault();
}
};
return (
<select name="pets" id="pet-select" ref={selectRef}>
<option value="">--Please choose an option--</option>
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="hamster">Hamster</option>
<option value="parrot">Parrot</option>
<option value="spider">Spider</option>
<option value="goldfish">Goldfish</option>
</select>
);
};