Hello friends!
I’m doing a React exercise and I’d like to change the color of the count(number) .
When it increases(positive +) I want the color to be green and when it decreases(negative -) I want the color to be red.
Can somebody help me please?
Thanks
yes, the color should be red when the count is less than 0 and green when it greater than 0. No need to be changed when it equal to 0
Thanks in advance
You can add a color property to the state object and then in your increment and decrement functions you will need to write conditions on when the color should change based on if it is positive or negative.
Also, you could go one step further and create a helper function for getting a color:
// This function could be defined outside of your component, even
// in separate file
function getColor(num) {
if (num > 0) {
return 'green';
}
if (num < 0) {
return 'red';
}
return 'black';
}
// Then in your component's render method
render() {
return (
<h1 style={{ color: getColor(this.state.count) }}>Hello inline-styles</h1>
)
}
@jwilkins.oboe I think there is no need to add a new piece of state for that, because the color can be computed just by using the existing count state
Sure, then we can replace the ternaries with if statements to make it more clear
render() {
let color;
if (this.state.count > 0) {
color = 'green';
}
if (this.state.count < 0) {
color = 'red';
}
return (
<h2 style={{ color }}>{this.state.count}</h2>
)
}