How to conditionally render React component ?

Welcome to the weekly series on JavaScript ecosystem. Today we are going to look at how can you conditionally render a React component in your app. We will take a look at a very simple example in this video. Based on a condition we will either render a component that display the image of this coffee or it will render the image of tea. So let’s dive in to the code.

Full Transcript

Hi there and welcome to the weekly series on JavaScript ecosystem. Today, we are going to look at how you can conditionally render a react component in your app. We will take a look at a very simple example in this video. Based on a condition, we will either render a component that display the image of this coffee, or it'll render the image of a tea. So let's dive into the code. I'm using codesandbox here to spin up a react app and inside this app.js file, I simply render this component with a text wrapped inside headline2. There are two PNG files I have added to the src directory and this App component will render an image based on the value of this variable displayTea. It's value is initially false. Now our goal is to render the image of a tea when displayTea is true. Otherwise we want to render the image of a coffee inside this component. In react, you can embed any expression in JSX, if you wrap them in curly braces ({}). And that's what we will do here, we will also use an inline if with a logical and operator to ensure that the app component renders a tea when displayTea is true, otherwise it will render the image of the coffee.

This is a clever approach because of the way logical and works it evaluates from left to right. So if displayTea is true, then your element on the right side of the logical and will be the output. If displayTea is false, then the element on the left side of the logical and will be evaluated, which is false. So react is going to ignore it. To fix the errors, we will add the imports for both tea and one for coffee. Let's also quickly add an inline style so that the height is 20 vh for both the images. Since the value of displayTea variable is false, we see the coffee image being rendered. Let's go ahead and change the value to true. And you can see that the component is rendered with the image of tea. So this is a pretty neat way of writing the code for conditional rendering, rather than writing separate components to render 2 different images. However, if your component has a complex hierarchy, then it makes sense to abstract that code out into a smaller component. That's all I wanted to cover in this video. I hope that's helpful, and I'll see you in the next video.