MyInternships.in

Components & Props

React Conditional Rendering

Conditional rendering means showing different JSX depending on state or props. React has no special directive for it — you use ordinary JavaScript: ternaries, the logical AND operator, early returns, or a variable computed before the return.


What is Conditional Rendering in React?

Conditional rendering means showing different JSX depending on state or props. React has no special directive for it — you use ordinary JavaScript: ternaries, the logical AND operator, early returns, or a variable computed before the return.

Why Conditional Rendering matters

Loading spinners, empty states, error messages, logged-in versus logged-out headers — practically every real screen branches on some condition.

Conditional Rendering example

Four ways to branch
JSX
// 1. Ternary — pick one of two
{isLoading ? <Spinner /> : <JobList jobs={jobs} />}

// 2. && — render or nothing
{error && <p className="error">{error}</p>}

// 3. Early return — skip the whole component
if (!user) return <LoginPrompt />;

// 4. Variable — best when there are many branches
let content;
if (status === 'loading') content = <Spinner />;
else if (status === 'error') content = <ErrorBox />;
else content = <JobList jobs={jobs} />;
return <main>{content}</main>;

How this works

All four are plain JavaScript. Use && only when the left side is a genuine boolean, because React renders the number 0 — so a count of zero would print "0" on screen instead of nothing.

What React renders for falsy values

ValueRendered output
false, null, undefinednothing
0the character 0 — a common bug
'' (empty string)nothing
NaNthe text NaN

Common mistakes with Conditional Rendering

  • Writing {items.length && <List />} — with zero items this renders "0".
  • Nesting ternaries three deep, which becomes unreadable; use a variable or early returns instead.
  • Rendering a component conditionally when you meant to hide it with CSS — conditional rendering unmounts it and destroys its state.
💡

Guard length checks explicitly: {items.length > 0 && <List />}. It costs four characters and removes a whole class of bug.

React Conditional Rendering— Interview Questions & FAQs

Why does 0 show up on my page?+

You used {count && <Something />}. React renders the number 0 as text. Convert the condition to a real boolean: {count > 0 && <Something />}.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships