Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
How to use conditional commands inside the switch in React

I wrote a program that by pressing the ArrowUp button I want to first check the mode inside Print the switch according to the mode on the console And I have a button to change the mode I do not know why the conditional statement inside the switch does not work I also want the switch to be inside useEffect please guide me

import { useEffect, useState } from "react";

export default function App() {
  const [mode, setMode] = useState("one");

  useEffect(() => {
    const keyDownCallback = function (e) {
      switch (e.keyCode) {
        case 38:
          mode === "one" ? console.log("one") : console.log("two");
          break;
      }
    };
    document.addEventListener("keydown", keyDownCallback);
    return () => document.removeEventListener("keydown", keyDownCallback);
  }, []);
  
  function handleChangeMode() {
    return mode === "one" ? setMode("two") : setMode("one");
  }

  return (
    <div style={{ textAlign: "center" }}>
      <h2>View the output on the console</h2>
      <button onClick={handleChangeMode}>change mode</button>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Edited: Working example with minimal changes for you new code. The only thing I changed was to add [mode]to useEffect

You declare a the function keyDownCallback in useEffect that is never used. That is why you don't get your prints.

about 4 years ago · Juan Pablo Isaza Relatório

0

The switch case works fine, the problem is the way you are using useEffect.
You need to add a dependency for mode in order to be able to switch modes and print accordingly. Also providing a default case is crucial.
https://codesandbox.io/s/beautiful-https-6ol4zw?file=/src/App.js

And in case you want the mode to toggle with every click, you can simply move the toggling logic inside the listener's callback function.
https://codesandbox.io/s/winter-haze-29inyy?file=/src/App.js

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda