Please help me with this react exercise

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

Here is the link: https://codepen.io/mike5485/pen/WNpNXEO?editors=0010

Hello :wave:

Just to clarify, should the color be red when the count is less than zero or anytime you click on decrease button?

1 Like

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

Hi @mike2020 !

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.

Then you can add style to your h2 element

style={{color: this.state.color}} 

That’s what I would do :grinning:

Oh okay, then it shouldn’t be a problem :slight_smile:

You could use inline styles for that when rendering the count. Here’s an example:

render() {
  const count = this.state.count;
  const countColor = count > 0 ? 'green' : count < 0 ? 'red' : 'black';

  return (
    <h1 style={{ color: countColor  }}>Hello inline-styles</h1>
  )
}

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 :smiley:

1 Like

Also, I removed the link from your post since we can’t click on them.

Yeah, that’s true too.
Still not a fan of nested ternaries though :laughing:
Most of the time they make my brain hurt

It works…!
Thanks so much my dear frends…!

1 Like

Sure, then we can replace the ternaries with if statements to make it more clear :smiley:

  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>
    )
  }
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.