1

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

1

3 Answers 3

2

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 === " " )
Sign up to request clarification or add additional context in comments.

Comments

1
  • There's deferant between 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 following
if(e.key === "Enter") {
  //Some code
} else if(e.key === " " || e.key === "Spacebar") {
 //Some code
}
  • on the other side there's also e.code who will return space as Space if you want to use Space you can make your code like that
if(e.key === "Enter") {
  //Some code
} else if(e.code === "Space") {
 //Some code
}

Comments

0

I think it's because of this: e.key === 'Space' it should be e.key === 'Spacebar'.

1 Comment

Spacebar is used only by some antique browsers, according to this: developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.