Rendering a component is easy.
But what if you want to render a specific HTML element or React component depending on a prop or state value?
In this article will cover a few techniques to add conditional rendering to your React render method.
In this article I will be using React state and props, and their new hook API.
If you’re not familiar with React state, props or their hooks please hop on over to the links listed below to get caught up.
This is one of my favorite methods to add conditional logic inside the render method.
It’s clean, and short.
In line 4, I’ve created a state key called yellAtPerson with a default value of false.
In line 8, I’m adding a condition to check if I need to yell at the person or not.
You might have notice 2 oddly looking symbols, && and ||.
When you’re using &&, you actually need to have one evaluation on the left side and the output on the right side.
e.g. – 3 > 1 && console.log(”3 is greater than 1″)
This is equivalent to
Back to the React example above, yellAtPerson is false, and the results to the expression failing.
So I do not yell at the person, and than || gets executed instead.
|| is short for or. That’s the of the else in a if-else condition.
Let’s yell at a person now.
In line 6-8, I’m using React useEffect to trigger only on componentDidMount.
And inside the hook function I’m setting yellAtPerson to true.
Another method is to use the short-hand version of an if-else statement.
This looks great, let’s plug into a React component version.
You may also add more HTML or React components by wrapping parenthesis around them.
This style might get a bit too clutter and messy to read.
But it’s up to you to decide what is a readable, and appropriate style to use for you and your team.
I’ve been doing a lot of talk about how to write short-hand versions of an if-else statement, but what if you want to use a regular if-else statement syntax?
Great news, you can!
Another example of preventing a React component to render is to have it return null.
This is mostly useful of drop-down menus, or modals.
In the example above, I’ve created a new React component called Modal.
The Modal component will check in line 4, if it needs to display the H1 element or not.
I’m using the Modal component inside my SampleComponent, and I’m passing my state showModal as a property.
I’ve also added a button with a click handler. The handler function will toggle on/off the value of showModal.
This will cause a toggle effect in our React application.
You might be asking yourself, which is the best way to write conditions inside the React render method.
In my humble opinion, there is no correct way or best method.
Pick the one that is the most readable for you and your team for that specific use-case.
There have been plenty of projects I’ve jumped into where, the app is using all the methods available in 1 React component.
But the code was readable and clear, so it didn’t cause any issues.