Reputation: 488
Im having problem changing text color based on either the count is increasing or decreasing while also having the ability to change color through click event, how do I solve this. Sorry Im new to react.
import React, {useState, useEffect} from 'react';
function Counter() {
const [count, setCount] = useState(0)
const increase = () => setCount(count + 1);
const decrease = () => setCount(count - 1);
const [prevCount, setPrevCount] = useState(count);
const [color, setColor] = useState('yellow')
useEffect(() => {
if (count > prevCount) {
setPrevCount(count - 1);
}
}, [count])
function handleColorChange() {
const nextColor = color ==='green'? "red" : "green"
setColor(nextColor)
}
return (
<div className="App">
{console.log(prevCount)}
<button onClick={increase}>
increase
</button>
<button onClick={handleColorChange}>
toggle color
</button>
<button disabled={count <= 0} onClick={decrease}>
decrease
</button>
<br/>
<p style={{color, fontSize: "20px", fontWeight: "bold"}}>{count}</p>
</div>
);
}
export default Counter;
Upvotes: 2
Views: 4217
Reputation: 15708
Based on your explanation, why don't you just configure the increase
function to set the color to green, and the decrease
to red?
const increase = () => {
setCount(count + 1);
setColor("green");
};
const decrease = () => {
setCount(count - 1);
setColor("red");
};
Upvotes: 1