Conditional rendering
- React Native course
- Beginner
- Lesson 11/116
- 5 min
Learn conditional rendering with && and ternary.
Conditional rendering
Sometimes you want to show a component only under a certain condition. This is called conditional rendering. JSX has two common methods for this.
The first is the && operator: {isLoggedIn && <Text>Welcome</Text>}. If the condition is true the right side appears; if false nothing is shown.
The second is the ternary operator: {isLoggedIn ? <Text>Yes</Text> : <Text>No</Text>}. If true the first side appears; if false the second side appears.
Ternary operator
The ternary operator has three parts: condition ? trueValue : falseValue. If the condition is true the first value is returned; otherwise the second value.
It is used inside JSX with curly braces: {count > 0 ? <Text>Full</Text> : <Text>Empty</Text>}. This shows two different outputs in one line.
The ternary is the one-line equivalent of if-else. Since if cannot be used inside braces, ternary is preferred.
Practice Render with ternary
Define a variable isLoggedIn (const isLoggedIn = true;). The App component should use a ternary inside a <View> for conditional rendering: if true show <Text>Welcome</Text>, if false show <Text>Sign in</Text>.
Starter code
// Define isLoggedIn
// Write App with ternary
function App() {
return null;
}Sample solution
const isLoggedIn = true;
function App() {
return (
<View>
{isLoggedIn ? <Text>Welcome</Text> : <Text>Sign in</Text>}
</View>
);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 && operator
{____ && <Text>Welcome</Text>}
{isLoggedIn && <Text>Welcome</Text>}
Explanation: If isLoggedIn is true the Text appears.
2 Conditional render symbols
| Term | Meaning |
|---|---|
&& |
And operator |
? |
Ternary question |
: |
Ternary colon |
{ } |
Embed expression |
3 Which ternary form is correct?
- {isLoggedIn ? <Text>Yes</Text>}
- {isLoggedIn ? <Text>Yes</Text> : <Text>No</Text>} Correct answer
- {if (isLoggedIn) <Text>Yes</Text>}
- {isLoggedIn <Text>Yes</Text>}
Explanation: The ternary uses ? and : for two values.