How can I dynamically change part of text inside a reactjs render?

Issue

I have a row of text that should change depending on two different conditions. The first condition works well, it changes the text back and forth between ‘Completed: ‘ and and empty string ”. As below.

render() {
    return(
    <div className={container}>
                {(this.conditionOne ? 'Completed: ' : '') + this.completedValue + '%'}
    </div>
    )
}

The second condition is what I can’t get working. It is only supposed to change the second part of the text, i.e. this.completedValue + '%‘. My first instinct was to wrap that part up in a div and then change the CSS for that specific div as I tried here.

render() {
    return(
            <div className={container}>
                {(this.conditionOne ? 'Completed: ' : '') + 
                    <div className={this.conditionTwo? 'conditionTwoDiv' : ''}>
                        {this.completedValue + '%'}
                    </div>
                }
            </div>
    )
}

This only renders "Completed: {Object Object}". The only thing I want to do is to change the color of the text when this.ConditionTwo is true┬┤, but I can’t figure out how to do this without either having a huge nest of conditions or changing the whole text and not just the last part.

As you probably understand from question I’m not the best with this syntax or programming in general so explanations that help me understand why something is working or not are extra appreciated. Thank you!

Solution

You should use span to add string like this:

<span>
  {this.conditionOne && "Completed: "}
  <span className={this.conditionTwo ? "conditionTwoDiv" : ""}>{this.completedValue + "%"}</span>
</span>

Answered By – Viet

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published