Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

117
Vistas
React.js only reading first if statement

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

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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 === " " )
about 4 years ago · Juan Pablo Isaza Denunciar

0

  • 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
}
  • but for better support use e.key here's a list with key values
  • also there's some other things like e.keyCode who is deprecated so avoid use it
about 4 years ago · Juan Pablo Isaza Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda