Back to Blog
Lesson 10 of the React Fundamentals: Build Modern UIs from Scratch course
ReactJune 25, 20263 min read

Conditional Rendering: Mastering UI Logic in React

Learn how to use conditional rendering in React to display UI elements dynamically. Master ternary operators and logical operators to build cleaner interfaces.

Reactfrontendweb developmentJSXjavascript

Previously in this course, we discussed Passing Data with Props and Dynamic Movie Cards, where we learned how to feed data into our components. Now, we'll take that data and make our UI smarter by implementing conditional rendering.

In professional development, you rarely show every element at all times. Perhaps a movie is missing a rating, or an image failed to load. Instead of breaking the UI, we use conditional rendering to show fallback states or hide elements entirely.

Understanding UI Logic in JSX

At its core, React is declarative. You tell React what the UI should look like based on the current state or props, rather than manually reaching into the DOM to hide or show elements. Because JSX is just JavaScript, we use standard language features—like the ternary operator and logical AND (&&)—to decide what gets rendered.

1. The Ternary Operator

The ternary operator is the bread and butter of React conditionals. It’s perfect for "either-or" scenarios.

JSX
// Syntax: condition ? (render if true) : (render if false)
{isFeatured ? <Badge text="Featured" /> : null}

2. The Logical AND (&&)

Use the && operator when you want to show an element only if a condition is true, and show nothing if it's false.

JSX
// Syntax: condition && (render if true)
{hasDiscount && <p>Price: $9.99</p>}

Worked Example: Enhancing the MovieCard

Let's return to our movie-browser project. Currently, our MovieCard component displays data blindly. If a movie is missing a "release year" or has no "rating," we might end up with empty HTML tags or awkward layout gaps.

Let's update our MovieCard to handle these scenarios gracefully.

JSX
function MovieCard({ title, year, rating, isPopular }) {
  return (
    <div className="movie-card">
      <h2>{title}</h2>
      
      {/* Conditionally render the year only if it exists */}
      {year && <p>Released: {year}</p>}
      
      {/* Use a ternary to show a special tag for popular movies */}
      <div className="status">
        {isPopular ? (
          <span className="badge-hot">Trending Now!</span>
        ) : (
          <span className="badge-normal">Standard</span>
        )}
      </div>
      
      {/* Display rating only if it's greater than 0 */}
      {rating > 0 ? <p>Rating: {rating}/10</p> : <p>No ratings yet</p>}
    </div>
  );
}

By keeping our logic idempotent—ensuring that the same inputs always result in the same UI output—we avoid the common bugs associated with imperative DOM manipulation, as discussed in React Rendering: Why Your Logic Must Be Idempotent.

Hands-on Exercise

Open your project and locate your MovieCard component. Perform the following steps:

  1. Add a genre prop to your MovieCard.
  2. Update the JSX to render the genre only if the genre prop is provided.
  3. If the genre is missing, render a small <small>Genre unknown</small> tag instead.
  4. Test it by passing a movie object with the genre and one without.

Common Pitfalls

  • The "0" Bug: If you use count && <Component /> and count is 0, React will render the number 0 on your screen. This happens because 0 is a falsy value in JavaScript, but React treats it as a valid node to render. Always ensure your condition is a strict boolean (e.g., count > 0 && <Component />).
  • Over-nesting: Avoid nesting multiple ternary operators inside each other. It becomes unreadable very quickly. If your logic is complex, it’s often cleaner to extract it into a helper function or a separate small component.
  • Side Effects in JSX: Never perform data fetching or state updates directly inside your JSX conditional blocks. JSX is strictly for describing the UI. For more on managing complex logic, see React Conditional Rendering: Mastering Guard Clauses and Ternary Chains.

Recap

Conditional rendering is how we make our components responsive to the data they receive. By leveraging the ternary operator for binary choices and the && operator for existence checks, we keep our UI clean and resilient. Remember: keep your logic simple, avoid rendering falsy numbers, and prioritize readability.

Up next: We'll take our dynamic MovieCard components to the next level by learning how to handle collections of data with Rendering Lists of Data.

Similar Posts