Conditional rendering

web
mobile

Author: Dawid Adach

-

1. Using IF - ELSE


Currently, we have a list of events on our agenda:

            events: [
            {
              id: 1,
              time: "10:00",
              title: "Breakfast with Simon",
              location: "Lounge Caffe",
              description: "Discuss Q3 targets"
            },
            {
              id: 2,
              time: "10:30",
              title: "Daily Standup Meeting (recurring)",
              location: "Warsaw Spire Office"
            },
          [...]
          ]
          
      
but for some of them the parameters like location or description are optional. Currently, our render() method doesn't check whether a value exists:

            <React.Fragment>
                <h3>
                    {this.props.time} - {this.props.title}
                </h3>
                <h6>Location: {this.props.location}</h6>
                <p>Desc: {this.props.description}</p>
            </React.Fragment>                  
     

As a result, we see empty values:



As you already know, we cannot use JS directly inside our render method. We could, however, offload the logic to separate functions as below:

            function Hello(props) {
                const isLoggedIn = props.isLoggedIn;
                if (isLoggedIn) {
                  return "Hello!";
                }
                return "Please login first!";
              }
              ReactDOM.render(
                // Try changing to isLoggedIn={true}:
                <Hello isLoggedIn={false} />,
                document.getElementById("root")
              );              
      
That said, React provides us a more useful mechanism for conditional rendering called inline If with Logical && Operator. 

2. If with Logical && Operator


How does it work? Let's replace or Location heading with the following code:


            {this.props.location && <h6>Location: {this.props.location}</h6>}
      

As you can see we have wrapped it with curly braces and added a logical check followed by the logical && operator.

Note:
You can read it as an IF-THEN condition
"IF this.props.location exists THEN display content after &&"

Let's also update our description code:


            {this.props.description && (
                <p className="p-2 mb-4  blue-grey lighten-5 blue-grey lighten-5">
                  {this.props.description}
                </p>
              )}              
     

Preview:

Conditional rendering

3. Conditional blocks rendering


You can also apply the same logic to bigger blocks of code. Let's import a few more components from the MDB library: 


            import {MDBBtn, MDBInput, MDBModal, MDBModalBody, MDBModalHeader, MDBModalFooter, MDBIcon, MDBBadge, MDBContainer, MDBRow, MDBCol} from "mdbreact";
       

and update our render() method ins the Event component: 


            render() {
                return (
                  <React.Fragment>
                    <div className="media mt-1">
                      <h3 className="h3-responsive font-weight-bold mr-3">
                        {this.props.time}
                      </h3>
                      <div className="media-body mb-3 mb-lg-3">
                        <MDBBadge color="danger" className="ml-2 float-right">
                          -
                        </MDBBadge>
                        <h6 className="mt-0 font-weight-bold">{this.props.title} </h6>{" "}
                        <hr className="hr-bold my-2" />
                        {this.props.location && (
                          <React.Fragment>
                            <p className="font-smaller mb-0">
                              <MDBIcon icon="location-arrow" /> {this.props.location}
                            </p>
                          </React.Fragment>
                        )}
                      </div>
                    </div>
                    {this.props.description && (
                      <p className="p-2 mb-4  blue-grey lighten-5 blue-grey lighten-5">
                        {this.props.description}
                      </p>
                    )}
                  </React.Fragment>
                );
              }
            
     

As you can see we are using <React.Fragment> in a conditional rendering of a location item. We have also added some styles to our app. Now it looks much better:

Calendar app preview
Let's update also the App Class

            render() {
                return (
                  <React.Fragment>
                    <MDBContainer>
                      <MDBRow>
                        <MDBCol md="9" className="mb-r">
                          <h2 className="text-uppercase my-3">Today:</h2>
                          <div id="schedule-items">
                            {this.state.events.map(event => (
                              <Event
                                key={event.id}
                                id={event.id}
                                time={event.time}
                                title={event.title}
                                location={event.location}
                                description={event.description}
                              />
                            ))}
                          </div>
                          <MDBRow className="mb-4">
                            <MDBCol xl="3" md="6" className="mx-auto text-center">
                              <MDBBtn color="info" rounded>
                                Add Event
                              </MDBBtn>
                            </MDBCol>
                          </MDBRow>
                        </MDBCol>
                        <MDBCol md="3">
                          <h3 className="text-uppercase my-3">Schedule</h3>
                          <h6 className="my-3">
                            It's going to be busy that today. You have{" "}
                            <b>{this.state.events.length} events </b> today.
                          </h6>
                          <h1 className="my-3">
                            <MDBRow>
                                <MDBCol xs="3" className="text-center">
                                  <MDBIcon icon="sun" fixed />
                                </MDBCol>
                                <MDBCol xs="9">Sunny</MDBCol>
                              </MDBRow>
                              <MDBRow>
                                <MDBCol xs="3" className="text-center">
                                <MDBIcon icon="thermometer-three-quarters" fixed />                  
                                </MDBCol>
                                <MDBCol xs="9">23°C</MDBCol>
                              </MDBRow>
                          </h1>
                          <p>
                            Don't forget your sunglasses. Today will dry and sunny, becoming
                            warm in the afternoon with temperatures of between 20 and 25
                            degrees.
                          </p>
                        </MDBCol>
                      </MDBRow>
                    </MDBContainer>
                  </React.Fragment>
                );
              }
              
      

And remove any styles if they are present in the index.css file. Now our app looks much better! 

Preview:



As you noticed we have added small buttons that we will use to remove items from the list, as well as a button in the bottom which will show a new window to add events to our schedule. Let's move on to the next lesson where we will learn how to add and delete events!


Rate this lesson

Previous lesson Download Next lesson

Spread the word:
Do you need help? Use our support forum

About the author

Dawid Adach
For more than 5 years Dawid worked as an IT Consultant specializing in SOA/EAI/ESB in the banking domain. He gained experience working in countries like Netherlands, Belgium, Poland and India developing enterprise-class systems for the most prestigious companies. Since co-founding mdbootstrap.com & brandflow.net in 2016 he has been using and teaching technologies such as Angular, TypeScript, PHP, AJAX, Mongo, SQL, Hadoop Stack, Virtualization, Automation and many others...