Lesson 13 of 30
43%
Conditional Rendering
Sometimes you show a component. Sometimes you do not.
React has no v-if. You use JavaScript: if, &&, or a ternary.
If and return
javascript
Ternary for two options
javascript
You can return whole trees, not only strings.
javascript
&& for maybe show
If the left side is true, React renders the right side. If not, it renders nothing useful.
javascript
Careful with numbers. {count && <List />} hides List when count is 0, but also shows a 0 on the page.
Prefer {count > 0 && <List />} so the left side is a real boolean.
null means render nothing
javascript
Keep JSX readable
If a ternary nests more than once, pull variables out above the return.
javascript
Tip: Conditional rendering is just JavaScript. If you can write the if in a function, you can write it in a component.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.