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>
);
}```
Here is a minimal verifiable example
React.useState is used to count each plus and minus state.plus - minusplus + minussetPlus(0) and setMinus(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>