Languages

React - how to conditionally disable button?

3 points
Asked by:
Dirask Community
5460

Can you tell me how to conditionally disable Start/Stop buttons when the counter is already counting?

I wanted to prevent another counter from being set by double-clicking the Start button.

My code:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const App = () => {
  const [counter, setCounter] = React.useState(0);
  const intervalRef = React.useRef();

  const startCounter = () => {
    intervalRef.current = setInterval(() => {
      setCounter((prevCounter) => prevCounter + 1);
    }, 1000);
  };

  const stopCounter = () => {
    clearInterval(intervalRef.current);
  };

  return (
    <div>
      <h2>{counter}</h2>
      <div>
        <button onClick={startCounter}>Start counter.</button>
        <button onClick={stopCounter}>Stop counter.</button>
      </div>
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
1 answer
3 points
Answered by:
Dirask Community
5460

I found a solution and made an article - React - setInterval example.

Quick solution:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const App = () => {
  const [counter, setCounter] = React.useState(0);
  const [counting, setCounting] = React.useState(false);
  const intervalRef = React.useRef();

  const startCounter = () => {
    intervalRef.current = setInterval(() => {
      setCounter((prevCounter) => prevCounter + 1);
    }, 1000);
    setCounting(true);
  };

  const stopCounter = () => {
    clearInterval(intervalRef.current);
    setCounting(false);
  };

  return (
    <div>
      <h2>{counter}</h2>
      <div>
        <button disabled={counting} onClick={startCounter}>Start counter.</button>
        <button disabled={!counting} onClick={stopCounter}>Stop counter.</button>
      </div>
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
0 comments Add comment
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join