I'm making a textbox that either handlesclick on enter or changes text to SVG on space click. However, react is only considering the first if statement, using else works, but else if gets completely ignored.
textbox code:
<input type="text" id="textbox" contentEditable="true" className="grinputbox"
onChange={(e) => {setInput(e.target.value)}}
onKeyPress={twoCalls}
/>
TwoCalls function:
const twoCalls = (e) => {
if (e.key === "Enter") {
console.log("enter");
handleClick()
} else if (e.key === "Space") {
console.log("space");
toSVG()
}
}
It does console log enter on pressing enter, however no space on pressing space
There is no such key property as "Space". The value to check against for a user's press on the space key is a literal space character: " ". You can find this directly from https://keycode.info/ (press space), or indirectly from the MDN documentation. (The part that says "If the pressed key has a printed representation, the returned value is a non-empty Unicode character string containing the printable representation of the key.")
So in short, replace
else if (e.key === "Space" )
with
else if (e.key === " " )
e.key, e.code in key some browser return space as " " and in some old browsers return it as "Spacebar" if you want the most support for space with key you can make it like the followingif(e.key === "Enter") {
//Some code
} else if(e.key === " " || e.key === "Spacebar") {
//Some code
}
e.code who will return space as Space if you want to use Space you can make your code like thatif(e.key === "Enter") {
//Some code
} else if(e.code === "Space") {
//Some code
}
e.key here's a list with key valuese.keyCode who is deprecated so avoid use itI think it's because of this:
e.key === 'Space' it should be e.key === 'Spacebar'.