Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>
  );
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading