'How to count button clicks in RJSX
I have a simple counter app I am practicing. I have it setup so that each time Increase or Decrease is pressed, the count will change accordingly. But I want to count how many times each button is clicked in positive integers. My problem now is that whenever Count is below 0, numCount will subtract. Not sure what I'm doing wrong:
import './style.css';
import Count from './things.js';
export default function App() {
const [count, setCount] = useState(0);
const getColor = () => {
if (count === 0) return '#112a42';
return count < 0 ? 'red' : 'green';
};
const num = (numCount) => {
if (numCount >= 0) return numCount;
if (numCount < 0) return numCount * - 1;
};
return (
<div className="container">
<div className="main">
<Count text="What's the count?"/>
<h1 style={{ color: getColor() }} className="number">
{count}
</h1>
<div className="buttons">
<button
type="button"
className="decrease"
onClick={() => setCount(count - 1)}
>
Decrease
</button>
<button
type="button"
className="reset"
onClick={() => setCount(0)}
>
Reset
</button>
<button
type="button"
className="increase"
onClick={() => setCount(count + 1)}
>
Increase
</button>
</div>
<p className="paragraph"> You clicked {num(count)} times</p>
</div>
</div>
);
}```
Solution 1:[1]
Here is a minimal verifiable example
React.useStateis used to count eachplusandminusstate.- Counter is derived state and can be computed using
plus - minus - Total clicks is derived state and can be computed using
plus + minus - To reset,
setPlus(0)andsetMinus(0)
function App() {
const [plus, setPlus] = React.useState(0)
const [minus, setMinus] = React.useState(0)
function reset(event) {
setPlus(0)
setMinus(0)
}
return <div>
<button type="button" onClick={_ => setMinus(minus + 1)} children="-" />
{plus - minus}
<button type="button" onClick={_ => setPlus(plus + 1)} children="+" />
<br />
total clicks: {plus + minus}
<br />
<button type="button" onClick={reset} children="reset" />
</div>
}
ReactDOM.render(<App/>, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ??? |
