DRY in "Render If-Else condition"

For the React challenge “Render If-Else condition” I’ve made a render function like this:

  render() {
    // Change code below this line
    let display = ""
    if(this.state.display) {
      display = <h1>Displayed!</h1>
    }
    return (
       <div>
         <button onClick={this.toggleDisplay}>Toggle Display</button>
         {display}
       </div>
    );
  }

And don’t pass the test because

The render method should use an if/else statement to check the condition of this.state.display

Which is not truth ) And when I clicked Hint button and see that in solution it’s like this:

render() {
    // change code below this line
    if (this.state.display) {
      return (
         <div>
           <button onClick={this.toggleDisplay}>Toggle Display</button>
           <h1>Displayed!</h1>
         </div>
      );
    } else {
      return (
        <div>
           <button onClick={this.toggleDisplay}>Toggle Display</button>
         </div>
      );
    }
  }

I was like … Really? Isn’t it contrary DRY principle? What if I want to change a text on button?

The point of the exercise is how to use an if/else in JSX though.

1 Like

It is 100% true. You did not use if/else, you used if. As ArielLeslie pointed out, this was the point of the lesson. What you did basically does the same thing, but it doesn’t follow the directions. A big part of being a developer is paying attention to minute details.

1 Like