简体   繁体   中英

Button visibility based on app running state in Next.js

I'm trying to find the recommended pattern for implementing something like this in Next.js.

Basically, I have a mini app within a Next.js page. The page keeps state (called runningState). runningState can be stopped, running, or paused. I also have three buttons- Start, Pause, and Test. And I want to change the visibility of these buttons based on the running state. For example, Pause would be disabled if the 'app' isnt running. Test would be enabled only if the app is stopped or paused.

To control the buttons I am currently using DOM query selectors within useEffect. This approach seems hackish. I would prefer to use something like Refs so that I can control the elements directly, however it seems I can't use them with functional components? Another approach I had was to put the logic inside the buttons themselves but that also seems counter-intuitive and poorly scoped.

Currently:

    //app logic
    const startBtn = document.getElementById("start");
    const pauseBtn = document.getElementById("pause");
    const testBtn = document.getElementById("test");

    //app logic
    switch (runningState) {
      case 0:
        startBtn.classList.remove("running");
        startBtn.innerHTML = "Demarrer";

        pauseBtn.classList.add("disabled");
        pauseBtn.classList.remove("running");
        pauseBtn.disabled = true;
        pauseBtn.innerHTML = "Pause";

        testBtn.classList.remove("disabled");
        testBtn.disabled = false;

        break;
      case 1:
        startBtn.classList.add("running");
        startBtn.innerHTML = "Annuler";

        pauseBtn.classList.remove("disabled");
        pauseBtn.classList.remove("running");
        pauseBtn.disabled = false;
        pauseBtn.innerHTML = "Pause";

        testBtn.classList.add("disabled");
        testBtn.disabled = true;

        break;
      case 2:
        pauseBtn.classList.add("running");
        pauseBtn.innerHTML = "Redemarrer";
        testBtn.classList.remove("disabled");
        testBtn.disabled = false;

        break;
    }

So, is there some sort of pattern for this? Thanks

You can use useRef like below

  const startRef = useRef(null);
  const pauseRef = useRef(null);
  
  const onClickStart = () => {
    const button = startRef.current.className = ""; 
  };
   const onClickPause = () => {
    const button = startRef.current.className = "disabled"; 
  };
  
  <button ref={startRef} className="" onClick={onClickStart}>Start</button>
  <button ref={pauseRef} className="" onClick={onClickPause}>Pause</button>```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM