Lesson 10 of 15
Smart Interfaces (Conditional Rendering)
Lesson Updated: Apr 28, 2026
Requirement
Understand how to make your UI adaptable by showing or hiding parts of the screen based on specific conditions. Just like an app shows a "Log Out" button when you are signed in, and a "Log In" button when you are out, your components need logic to decide what to display.
Assignments (Start First)
- Simple beginner UI task: Create a
Greetingcomponent that takes anisLoggedInboolean prop. Use anif/elsestatement or a ternary operator to return an<h1>Welcome back!</h1>if true, and<h1>Please log in.</h1>if false. - Slightly improved version: Build a
LoadingSpinner. Create a state variableisLoadingset to true. Use the logical AND (&&) operator to show a "Loading data..." message. Add a button that setsisLoadingto false, which should make the loading message disappear and reveal a "Data loaded successfully!" message. - Practical real-world component: Create a
PricingTierCard. It accepts props fortitle,price, and a booleanisPro. IfisProis true, conditionally render a gold "Best Value" badge at the top of the card and append three extra premium features to the feature list. - "The Escalation": Build a
PasswordInputfield. Create an<input>element and a toggle button next to it. Use state to track whether the password should be visible. Use a ternary operator on the input'stypeattribute to switch between"password"(hidden) and"text"(visible) based on the state.
Lessons (Optional)
- Ternary Operator (condition ? true : false): The perfect JavaScript syntax for toggling between two different UI states directly inside your JSX.
- Logical AND (condition && <Component />): The best syntax for rendering something *only* if a condition is true, and rendering absolutely nothing otherwise.
- Early Returns: You can use a standard
ifstatement at the top of your component to return a fallback UI (like an error screen) before the rest of the component runs.
The Summary and Quizzes
- Concept explanation: Conditional rendering gives your app decision-making power, allowing it to react to user states, permissions, and loading phases.
- Why it works in React: React evaluates the JavaScript condition inside the curly braces
{}. If it evaluates tofalse,null, orundefined, React simply ignores it and renders an empty space in the DOM. - Challenge question: Rewrite the following code using the logical AND (
&&) operator:userHasErrors ? <ErrorBanner /> : null