DEV Community

Randy Rivera
Randy Rivera

Posted on

React: Render with an If-Else Condition

  • Another way of using JavaScript to control your rendered view is to tie the elements that are rendered to a condition. When the condition is true, one view renders. When it's false, it's a different view. We can do this with the basic if/else statement.
  • FreeCodeCamp has a class MyComponent which contains a boolean in its state which tracks whether you watn to display some element in the UI or not. The button toggles the state of this value. Right now, it render the same UI everytime. Let's rewrite the render() method with an if/else statement so that if display is true, you return the current markup. Otherwise, return the markup without the h1 element.
  • Code:
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      display: true
    }
    this.toggleDisplay = this.toggleDisplay.bind(this);
  }
  toggleDisplay() {
    this.setState((state) => ({
      display: !state.display
    }));
  }
  render() {
    // Change code below this line

    return (
       <div>
         <button onClick={this.toggleDisplay}>Toggle Display</button>
         <h1>Displayed!</h1>
       </div>
    );
  }
};
Enter fullscreen mode Exit fullscreen mode
  • Answer:
  render() {
    if (this.state.display === true) {
      return (
       <div>
         <button onClick={this.toggleDisplay}>Toggle Display</button>
         <h1>Displayed!</h1>
       </div>
    );
    } else {
      return (
        <div>
          <button onClick={this.toggleDisplay}>Toggle Display</button>

        </div>
      )
    }

  }
};
Enter fullscreen mode Exit fullscreen mode

Use && for a More Brief Conditional

  • You can also use the && logical operator to perform conditional logic in a more concise way. This is possible because you want to check if a condition is true, and if it is, return some markup.
  • Ex:
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      display: true
    }
    this.toggleDisplay = this.toggleDisplay.bind(this);
  }
  toggleDisplay() {
    this.setState(state => ({
      display: !state.display
    }));
  }
  render() {
    return (
       <div>
         <button onClick={this.toggleDisplay}>Toggle Display</button>
         {this.state.display === true && <h1>Displayed!</h1>}
       </div>
    );
  }
};
Enter fullscreen mode Exit fullscreen mode
  • If the condition is true, the markup will be returned. If the condition is false, the operation will immediately return false after evaluating the condition and return nothing. You can include these statements directly in your JSX and string multiple conditions together by writing && after each one.

Top comments (0)