Conditional Rendering
This lesson will teach you how to add Conditional Rendering in your application by using ternary operator.
We'll cover the following
Conditional rendering is usually introduced early in React applications, though not in our working example. It happens when you decide to render either of two elements, which sometimes is a choice between rendering an element or nothing. The simplest usage of a conditional rendering can be expressed by an if-else statement in JSX.
The result
object in the local component state is null
in the beginning. So far, the App component returned no elements when the result
hasn’t arrived from the API. That’s already a conditional rendering, because you return earlier from the render()
lifecycle method for a certain condition. The App component either renders nothing or its elements.
But let’s go one step further. It makes more sense to wrap the Table component, which is the only component that depends on result
in an independent conditional rendering. Everything else should be displayed, even though there is no result
yet. You can simply use a ternary operator in the JSX:
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy