Conditional rendering

Follow me on Twitter, happy to take your suggestions on topics or improvements /Chris

Conditional rendering is about deciding what to render given a value of a variable. There are different approaches we can have here:

  • render if true
  • ternary expression

Render if true

Let's have a look at the first version:

class Element extends React.Component {
  state = {
    show: false
  };

  const toggle = () => {
    this.setState({
      show: this.state.show
    });
  }

  render() {
    return (
      <React.Fragment>
        <div>some data</div>
        {this.state.show &&
        <div>body content</div>
        }
        <button onClick={this.toggle}></button>
      </React.Fragment>
    );
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

Above we can see that look at the variable show in our state and renders a div if show is truthy:

{ this.state.show &&
  <div>body content</div>
}
1
2
3

Ternary rendering

In this version we define a ternary expression and render different things depending on the value of our variable:

class Element extends React.Component {
  state = {
    loading: false,
    data: void 0
  };

  const toggle = () => {
    this.setState({
      show: this.state.show
    });
  }

  render() {
    return (
      <React.Fragment>
        {this.state.loading ?
        <div>loading...</div> :
        <div>{this.state.data}</div>
        }
      </React.Fragment>
    );
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

Let's highlight the ternary expression:

{ this.state.loading ?
<div>loading...</div> :
<div>{this.state.data}</div>
}
1
2
3
4

Using if, else if, else

And of course it is possible to use normal if, else if, else clauses when rendering, like so:

class Element extends React.Component {
  state = {
    loading: false,
    data: void 0
  };

  const toggle = () => {
    this.setState({
      show: this.state.show
    });
  }

  const click = () => {
    this.setState({
      loading: true
    });
  }

  getData() {
    if (this.state.loading) {
      return <div>loading...</div>;
    } else if(this.state.data) {
      return <div>{this.state.data}</div>;
    }
    return <div>{this.state.data}</div>;
  }

  render() {
    return (
      <React.Fragment>
        <div>something</div>
        { this.getData() }
      </React.Fragment>
    );
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

We can't use if, else if and so on directly in the template but we can have a method getData() that can decide for us what ot render out. Let's highlight what we did above, define a getData() method with conditional rendering:

getData() {
  if (this.state.loading) {
    return <div>loading...</div>;
  } else if(this.state.data) {
    return <div>{this.state.data}</div>;
  }
  return <div>{this.state.data}</div>;
}
1
2
3
4
5
6
7
8

and calling it in the template like so:

{ this.getData() }
1