EN
React - how to conditionally disable button?
1
answers
3
points
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
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