3 Ways to Dynamically Render UI in a React Component
Dynamic pages allow you to show users what they need without having any extra markup on the page diluting the user’s attention from what they are trying to do on your application.
Writing components that allow for that dynamic behavior can quickly get complicated if you are expecting a myriad of user behavior. I’m going to show you three ways you can add conditionals to your React components to render content dynamically.
1. The If-Else Condition
Probably the most explicit and easy to read is the if-else conditional. Let’s use the component below as our example.
We have a boolean in state and render a completely different snippet of HTML based on the value of that boolean. Here we are using a simple example, but based on different combinations you could continue in a similar manner to create a variety of behavior.
2. The && Logical Operator
The issue with the if/else statement is that you may have a certain piece of code that exists in multiple cases. This means you are going to have to re-write those snippets of code for each case they are needed. This gives off a bad code smell and begs for something less brittle.
In comes &&. Here’s the same component as above with a much more concise solution, but the same behavior.
What’s happening under the hood? The condition
this.state.display is being checked and when it returns
false it does not read the right side of the
&& operator and continues through the code. When the condition is
true the markup on the right side of the
&& is returned and made visible. If your component has a lot of if/else statements that return slightly different UI configurations this method might be a better option to avoid repeating your code and being prone to errors.
3. The Ternary Operator
condition_to_test ? execute_when_truthy : execute_when_falsy
Let’s use a different component for this one.
This component takes a user’s input and renders something dynamically based on that input. The ternary expression handles all of our UI cases by checking for the default case first then using a second ternary expression in the false check to give us our second and third render options.
I hope this comparison was helpful and can help you in your next project. Overall, I don’t think there is one option that is best for all situations here and I think a combination of these techniques is probably the best way to go.
Learn to code at home. Build projects. Earn certifications. Since 2014, more than 40,000 freeCodeCamp.org graduates…
React makes it painless to create interactive UIs. Design simple views for each state in your application, and React…
Connect with me:
MisterRK - Overview
Hi I'm Robert, a software engineer with a former life managing Michelin starred restaurants. I made the transition to…
Built as a part of a Udemy course on React best practices complete with a NoSQL database powered by Google Firebase…