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:
xxxxxxxxxx
1
// Note: Uncomment import lines while working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => {
6
const [counter, setCounter] = React.useState(0);
7
const intervalRef = React.useRef();
8
9
const startCounter = () => {
10
intervalRef.current = setInterval(() => {
11
setCounter((prevCounter) => prevCounter + 1);
12
}, 1000);
13
};
14
15
const stopCounter = () => {
16
clearInterval(intervalRef.current);
17
};
18
19
return (
20
<div>
21
<h2>{counter}</h2>
22
<div>
23
<button onClick={startCounter}>Start counter.</button>
24
<button onClick={stopCounter}>Stop counter.</button>
25
</div>
26
</div>
27
);
28
};
29
30
const root = document.querySelector('#root');
31
ReactDOM.render(<App />, root );
1 answer
3 points
I found a solution and made an article - React - setInterval example.
Quick solution:
xxxxxxxxxx
1
// Note: Uncomment import lines while working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => {
6
const [counter, setCounter] = React.useState(0);
7
const [counting, setCounting] = React.useState(false);
8
const intervalRef = React.useRef();
9
10
const startCounter = () => {
11
intervalRef.current = setInterval(() => {
12
setCounter((prevCounter) => prevCounter + 1);
13
}, 1000);
14
setCounting(true);
15
};
16
17
const stopCounter = () => {
18
clearInterval(intervalRef.current);
19
setCounting(false);
20
};
21
22
return (
23
<div>
24
<h2>{counter}</h2>
25
<div>
26
<button disabled={counting} onClick={startCounter}>Start counter.</button>
27
<button disabled={!counting} onClick={stopCounter}>Stop counter.</button>
28
</div>
29
</div>
30
);
31
};
32
33
const root = document.querySelector('#root');
34
ReactDOM.render(<App />, root );
0 commentsShow commentsAdd comment