Home Coding & Scripting Conditional Rendering in React (with TypeScript Examples)

Conditional Rendering in React (with TypeScript Examples)

288
0

Conditional rendering in React means deciding what should appear on the screen based on certain conditions. It’s one of the most common things we’ll do when building any React application.

This guide walks through the simplest ways to conditionally render UI in React, step by step, using TypeScript for all examples.

We’ll use a Modal component as the main example.


📌 Note for Learners

Most of the conditional rendering techniques you will see in this post are NOT specific to React — they come directly from JavaScript.
If you want the pure JavaScript version first, read our post: Understanding Conditional Rendering in JavaScript.

This post shows how those JavaScript ideas are applied inside React components using TypeScript.


🧑‍💻 How to Practice This

To try these examples yourself:

Test the UI by clicking buttons and observing how components appear and disappear based on state.

  • Set up a React + TypeScript project
    If you haven’t done this yet, follow: How to Install TypeScript and Set Up a Project
  • Open or create a file named App.tsx.
  • Copy each code block from this post into App.tsx one at a time.
  • Run your project using npm start, yarn start, or pnpm dev.

⭐ What Is Conditional Rendering?

Conditional rendering means:

  • Show a component only when something is true
  • Hide it when it’s false
  • Choose between two components
  • Show fallback text when data is missing

Most of the conditional logic comes from JavaScript, but React uses these conditions to decide what component tree to return.

Let’s start with the most beginner-friendly patterns.


⭐ 1. Rendering Components Conditionally Using &&

One of the simplest forms of conditional rendering is the logical AND operator.

type AppProps = {};

function App({}: AppProps) {
  const [showModal, setShowModal] = React.useState<boolean>(false);

  return (
    <div>
      <button onClick={() => setShowModal(true)}>Open Modal</button>

      {showModal && <Modal />}
    </div>
  );
}

How this works:

  • If showModal is true, <Modal /> is rendered
  • If false, nothing is rendered
  • This is clean, simple, and widely used

⭐ 2. Using the Ternary Operator (condition ? A : B)

Use this when you want one of two outcomes.

function App() {
  const [showModal, setShowModal] = React.useState<boolean>(false);

  return (
    <div>
      {showModal ? (
        <Modal />
      ) : (
        <p>The modal is currently hidden.</p>
      )}
    </div>
  );
}

Useful when you want to show fallback UI.


⭐ 3. Using || for Fallback Values

This is for text or simple values, not components.

type User = {
  name?: string;
};

function Greeting({ name }: User) {
  return <p>{name || "Guest User"}</p>;
}

⭐ 4. Rendering Nothing by Returning null

Components can return null, meaning “render nothing.”

type NoticeProps = {
  show: boolean;
};

function Notice({ show }: NoticeProps) {
  if (!show) return null;
  return <p>Important Notice</p>;
}

This is valid but should be used thoughtfully (more on this later).


⭐ 5. A Simple Modal Component (No Conditional Logic Inside)

Here’s a clean Modal component written in TypeScript:

type ModalProps = {
  title?: string;
  children?: React.ReactNode;
};

function Modal({ title, children }: ModalProps) {
  return (
    <div className="modal">
      {title && <h2>{title}</h2>}
      <div className="content">{children}</div>
    </div>
  );
}

Notice:

  • No checks for whether it should be shown
  • No return null inside
  • It simply renders what it is told to render

This keeps the component pure.


⭐ 6. Full Example With Parent Controlling Rendering

Putting it all together:

function App() {
  const [showModal, setShowModal] = React.useState<boolean>(false);

  return (
    <div>
      <button onClick={() => setShowModal(true)}>Open Modal</button>

      {showModal && (
        <Modal title="Hello!">
          <p>This modal is conditionally rendered using TypeScript.</p>
          <button onClick={() => setShowModal(false)}>Close</button>
        </Modal>
      )}
    </div>
  );
}

⭐ When Should a Component Return null?

Returning null inside a component is useful only when:

  • The component must stay mounted but display nothing
  • It acts as a wrapper, listener, or logic helper
  • You need it to maintain state or effects without rendering UI

For most UI components (modals, alerts, menus):

👉 It is cleaner if the parent decides whether to render the component.


⭐ Why Let the Parent Control the Rendering?

After seeing all the examples, this becomes easier to understand:

  • ✔ The parent knows when the UI should appear
  • ✔ The child should not decide whether it exists
  • ✔ Cleaner data flow (React is one-way: parent → child)
  • ✔ Better for animations, cleanup, and component lifecycle
  • ✔ More predictable and easier to maintain

In short:

The parent decides if the component is shown. The child decides how it looks.


⭐ Summary

Here’s what you learned:

✔ React uses JavaScript logic to conditionally render components

✔ Main patterns:

  • && → show component only when condition is true
  • ternary → choose between two UI options
  • || → fallback values
  • returning null → intentionally render nothing

✔ Parent-controlled rendering is cleaner and more React-friendly

✔ TypeScript fits naturally with these patterns

Previous articleUnderstanding Conditional Rendering in JavaScript
Next articleChoosing the Right Icons for Next.js with Tailwind CSS Project
Heartin Kanikathottu
As a seasoned Cloud and Security Architect, I’ve led transformative initiatives in key roles, including Vice President at Morgan Stanley, Principal Architect at Societe Generale, and Tech Lead & Cloud Security Architect at VMware, among others. I’m also an internationally published author with multiple books available on platforms like Amazon and O'Reilly. Notably, one of my books was recognized as the 8th best cloud computing book of all time in 2020, reflecting the impact of my contributions to the field. With over 15 professional certifications from providers such as Microsoft (Azure), Amazon (AWS), Oracle (Java), Pivotal (Spring), and IBM, I bring a wealth of expertise to my work. Academically, I hold dual Master’s degrees in Cloud Computing and Data Analytics. I’m passionate about sharing knowledge and mentoring others, which is why I actively speak at global technical forums such as Tech Opportunities Fest at Platform Calgary, Google's Kubernetes Meetup, Java User Group, Elasticsearch Meetup, and the Agile India Conference.

LEAVE A REPLY

Please enter your comment!
Please enter your name here