How To Implement React Conditional Rendering

How To Implement React Conditional Rendering

There are situations where you might want to render your component based on certain conditions.

With JavaScript syntax like if/else statements, &&, and ?: operator you can conditionally render JSX.

There is no point in overthinking it. it's as easy as it can get. Imagine you have two contents and you have to make a choice between either of them based on certain conditions; let's say conditions A and B. So we say if condition A is met do this otherwise do something else when condition B is met.

Conditionally Returning JSX

Now let's get to the fun part by getting our hands dirty with some code practice.

let's assume you have a to-do list component rendering several items which can be marked as done or not.


function List({ todo, isDone }) {
  return <li className="list">{todo}</li>;
}

export default function TodoList() {
  return (
    <section>
      <h1>Godswill To Do List</h1>
      <ul>
        <List 
          isDone={true} 
          todo="Get to the gym" 

        />
        <List
          isDone={true} 
          todo="Get to work"  
        />
        <List 
          isDone={false} 
          todo="Eat beans and plantain"  
        />
           <List 
          isDone={true} 
          todo="Practice my violin"  
        />
           <List 
          isDone={false} 
          todo="Complete my article"  
        />
      </ul>
    </section>
  );
}

Observe that some of the list components have their isDone prop actually set to true instead of false. We want to add a checkmark ✅ to done items if isDone ={true}.We can achieve this by using if/else statements.

If/Else Statement

Using the If/Else Statement we have the following:


if (isDone) {
  return <li className="list">{todo} ✅</li>;
}
return <li className="list">{todo}</li>;

What we are trying to do is simply add the check mark to any of the list items we have done.

function List({ todo, isDone }) {
  if (isDone) {
    return <li className="list">{todo} ✅</li>;
  }
  return <li className="list">{todo}</li>;
}
export default function TodoList() {
  return (
    <section>
      <h1>Godswill To Do List</h1>
      <ul>
        <List 
          isDone={true} 
          todo="Get to the gym" 

        />
        <List
          isDone={true} 
          todo="Get to work"  
        />
        <List 
          isDone={false} 
          todo="Eat beans and plantain"  
        />

         <List 
          isDone={true} 
          todo="Eat beans and plantain"  
        />
         <List 
          isDone={false} 
          todo="Eat beans and plantain"  
        />
      </ul>
    </section>
  );
}

From the code above, if the isDone prop is true, the code returns a list of items with the checkmark as an indication that the item has been done. In other words, we are rendering the checked list based on the condition that the isDone prop is set to true.

we can still make changes to the list components, by changing the value of the IsDone prop on any of the items.

It is possible to render Null in a situation where you don't want to return anything. Let's say we don't want to show done items on our list at all, how do we go about it? should we return a blank JSX?

In situations like this, we return null, because a component must return something.

function List({ todo, isDone }) {
  if (isDone) {
    return null
   /* at this point we returned null, which is another way of sying return nothing.*/
  }
  return <li className="list">{todo}</li>;
}
export default function TodoList() {
  return (
    <section>
      <h1>Godswill To Do List</h1>
      <ul>
        <List 
          isDone={true} 
          todo="Get to the gym" 

        />
        <List
          isDone={true} 
          todo="Get to work"  
        />
        <List 
          isDone={false} 
          todo="Eat beans and plantain"  
        />

         <List 
          isDone={true} 
          todo="Eat beans and plantain"  
        />
         <List 
          isDone={false} 
          todo="Eat beans and plantain"  
        />
      </ul>
    </section>
  );
}

By returning null, we are invariably saying all list components that have their isDone prop set to null should not be seen on our UI. only those yet undone should be seen.

You may have noticed some duplication in our render output in our previous example.

 return <li className="list">{todo} ✅</li>;

The code above is similar to the code below, with the checkmark as the only difference.

 return <li className="list">{todo}</li>;

Although the duplication in itself isn't bad or wrong, it may make our code harder to maintain. for example, if we want to change our className we have to change it in two places.

  if (isDone) {
      // we will have to change the className here
    return <li className="list">{todo} ✅</li>;
  }
   //we will also have to change the ClassName here as well.
  return <li className="list">{todo}</li>;
}

In situations like this, we have to conditionally include a little JSX so as to keep our code DRY (Don't Repeat Yourself).

Conditional (Ternary) Operator? :

We use the ternary operator to achieve the same thing as we did with the If/else statement but with less code.

instead of this:

  if (isDone) {
    return <li className="list">{todo} ✅</li>;
  }
  return <li className="list">{todo}</li>;
}

We can write it like this:

return(
<li className="list">
{isDone ? todo + '✅' : todo}
</li>
);

The above code can be read as "if isDone is true, then (?) render todo + "✅", otherwise (:) render todo".

Logical AND Operator (&&)

The javascript logical AND (&&) operator is another shortcut you will encounter especially as it has to do with the React conditional rendering.

The Javascript logical AND operator (&&) is normally used when we want to render some JSX when the condition is true, or render nothing if otherwise.

return (
  <li className="list">
    {todo} {isDone && '✅'}
  </li>
);

We can read the above code as; "if, then (&&) render the checkmark, otherwise, render nothing. The Checkmark can only render if isDone is true

Implementing it on our todo we have the following.

function List({ todo, isDone }) {

      return (
    <li className="list">
      {todo} {isDone && '✅'}
    </li>
  );

}
export default function TodoList() {
  return (
    <section>
      <h1>Godswill To Do List</h1>
      <ul>
        <List 
          isDone={false} 
          todo="Get to the gym" 

        />
        <List
          isDone={true} 
          todo="Get to work"  
        />
        <List 
          isDone={false} 
          todo="Eat beans and plantain"  
        />

         <List 
          isDone={true} 
          todo="Practice my violin"  
        />
         <List 
          isDone={true} 
          todo="Complete my article" 
        />
      </ul>
    </section>
  );
}

Javascript && expression usually returns the value of its right side, if the left side is true. But if the condition is false, the whole expression becomes false.

I made some changes in our code just to show that the three methods do the same thing.

I change the props value of the first and last list components to false and true respectively.

Conclusion

You've been able to learn React conditional rendering. now it's time to build some cool stuff.