REACT / LESSON 04
Conditional Rendering.
Learn how to show, hide, and switch between different UI elements based on conditions in React

Loading the lesson…
Loading activities…
REACT / LESSON 04
Learn how to show, hide, and switch between different UI elements based on conditions in React

Loading the lesson…
Loading activities…
Your app has to show different things in different situations. A loading spinner while data is fetching. An error message when something breaks. A welcome screen for brand new users and a dashboard for the ones who are logged in. That's conditional rendering, which just means showing different UI depending on what's true right now.
The most common pattern is picking one of two things to show. For that you use a ternary operator (condition ? a : b).
When isLoggedIn is true, the user sees "Welcome back!" and when it isn't, they see "Please sign in." A ternary ALWAYS renders something, because it always picks one of its two branches.
Sometimes you want to show something or nothing at all. The && operator is perfect for that.
If hasUnread is true, the badge shows up. If it's false, nothing renders. Nice and clean.
When the conditions get more complicated, you can just return early from your component function.
Early returns keep your main render logic tidy. Every weird case gets handled and returned up top, before you ever reach the "happy path" at the bottom.
You can also stash JSX in a variable and render it later. That comes in handy when the logic for deciding what to show gets a lil hairy.
Showing or hiding one element is only half the story. A lot of the time you'll need to render a whole list of items, and the map() array method is how you turn data into JSX.
Each call to map() turns one array (of data) into another array (of JSX elements). Then React renders everything in that returned array.
When you render a list, every item needs a unique key prop. Keys tell React which item is which, so it can update the list efficiently when items get added, removed or shuffled around.
You can filter a list before you map it, or tuck conditions right inside your map.
That example filters the tasks, shows a message if nothing's left, renders whatever IS left, and slaps an "Urgent" badge on the high-priority ones. Every pattern from this lesson, working together in one component.
You can also switch CSS classes on and off to change how things look.
That's the exact pattern behind tabs, navigation items and toggle buttons that highlight whichever one is active.
? :) to pick between two elements&&) to show something or nothingmap() to turn arrays of data into lists of elementsYour components can show different things based on conditions now. But how do people actually interact with your app? Next lesson is event handling, which covers responding to clicks, typing, form submissions and more...