5

The Ultimate Guide to Conditional Rendering in React

 1 year ago
source link: https://blog.bitsrc.io/the-ultimate-guide-to-conditional-rendering-in-react-1-3f3a436c0374
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

The Ultimate Guide to Conditional Rendering in React

1*INeXmYcnSpGNYehSwWyEmA.png

Intro

To be a successful front-end developer, you must keep improving your code writing skills and knowledge about different ways to do the same task. No matter if you are a junior, mid, or senior developer, you have to be open-minded and willing to learn new techniques because what you knew four years ago, might be a bad practice today.

Conditional statements are used to execute various actions on various conditions, thus giving us the freedom to manage data in our application. In React, conditional rendering refers to the process of delivering and showing components based on certain conditions. These statements can be used to:

  • modify UI for users depending on their roles like “paid user”, “logged out user”, “administrator” etc.
  • show or update certain elements according to fetched data
  • hide or show certain elements and so on

There is more than one way to use conditional rendering in React. One problem can have multiple solutions and this is the case in this process.

In this guide, you will learn a whopping thirteen techniques to use for conditional rendering! Because this is a huge topic, this guide will be split into three parts and will be fully released next week, thus do not forget to follow me to not miss out on those articles.

0*taSQLyki_hebvimv.gif

Follow to see future articles

Conditional rendering techniques for this part are:

  • If-Else statement
  • Ternary operation
  • Inline IF with Logical && operator (Short Circuit Evaluation)

Conditional Rendering approaches

If-Else statement

Let’s start with the simplest example — andif-else statement. It will execute actions contained in the if block when the condition or conditions are satisfied. If that is not the case, it will execute the actions contained in the else block.

Let’s create a scenario, where you do not want to render your component because it does not have the necessary props for it. For example, you have a list of meals. Every meal has its own component. However, showing only one or two meals is not good enough, because you are selling exactly three meals every day. If there are less than three meals on the list, you want to return nothing, until the administrator decides to add more of those meals. You can use an if statement to return earlier from the render lifecycle.

If the list is empty, the component will return nothing. However, if you decide to show a text of some sort when a list is empty, you can do that. This will give some feedback for a better user experience.

In conclusion, if-else technique is the simplest among others.

Ternary operation

The conditional operator is the only JavaScript operator which takes three operands. It is similar to if-else statement. This lets us create if-else statements more concise. A default template looks like this:

contition ? expr1 : expr2

Let’s create an example. Imagine you have a toggle to switch between two modes: edit and view in your component. You have a simple boolean variable to decide which mode to render.

If you are writing a lot of code into branches of ternary operation, you can use parentheses. This helps with code readability.

In conclusion, ternary operation is more concise than a simple if-else statement, however, for complicated comparisons and components, it may impact readability as project grows, thus do not overuse it.

Inline IF with Logical && operator (Short Circuit Evaluation)

In the previous method, we could choose if we wanted to render the first or second component, however, It happens often, that you may want to render either an element or nothing.

For that, we have && boolean operator which means “and”. To get a “true” value, all statements must be true.

This is also known as Short Circuit Evaluation. It is a technique used to make sure there are no side effects during the evaluation of operands in an expression.

To better explain this operator, here are a few examples:

  • true && “This will render” will return “This will render”
  • false && “This will not render” will return nothing

Let’s see a better example. You are selling door knobs. When they are sold you want to show a notification list for yourself and when the list is empty, you want to show nothing.

When the length of the array is more than 0, the list will be printed. And when it is empty, only the <h1> element will be rendered.

Beware that overuse of this technique may become cumbersome and unintuitive as your application grows.

I will also show you how to fetch data from an API and display it using && operator. The following example shows you just that.

In the above example, we fetch data from an API using Axios. When the API returns a response, we update the state and use logical && operator to only render the data only when it’s available.

Selecting a Conditional Rendering Approach

Having multiple solutions to one problem may have a big effect on your project. It will affect code readability and effectiveness. There are some tips and rules on how to choose a conditional rendering technique:

  • Do not change the position of components on the basis of random choice in order to prevent components from mounting and remounting unnecessarily
  • Do not bloat your components within the return statement as this will cause components to delay in rendering
  • Change only the markup that is concerned with the conditional rendering
  • For situations where there are two outcomes, I would recommend using the ternary operator.
  • This list will expand when the other two articles are released

It is important to understand, that there are more factors on which technique you will choose, including your programming style, how complete the conditional logic is and your level at JavaScript and JSX.

You should always favour simplicity and readability, in other words, do not overdo it.

0*mZwr9QwdnZkDZzeo.gif

Clap clap clap! It means a lot to me :)

Conclusion

In summary, in this article, you read about the first three techniques of Conditional Rendering for React applications and got a few tips on how to choose those techniques and how to use them. More techniques will be shown in the next article thus follow me to not miss out on that!

Go composable: Build apps faster like Lego

1*mutURvkHDCCgCzhHe-lC5Q.png

Bit is an open-source tool for building apps in a modular and collaborative way. Go composable to ship faster, more consistently, and easily scale.

Learn more

Build apps, pages, user-experiences and UIs as standalone components. Use them to compose new apps and experiences faster. Bring any framework and tool into your workflow. Share, reuse, and collaborate to build together.

Help your team with:

Micro-Frontends

Design Systems

Code-Sharing and reuse

Monorepos


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK