REACTJS • LESSON 10 OF 36

React Component Conditional Rendering

Build components that explain which records qualify.

Read the explanation, run the worked example, then complete the matching Examples and Assignments tabs. Your original materials remain available alongside these notes.

Understand the idea

A reusable component can choose a branch from its props and return null when it has nothing to show. A collection component can filter records before creating children. For your pizza exercise, store an explicit vegetarian flag and display both a label and a visual indicator.

Conditional visibility affects state: removing a component removes its local state. Hiding it with CSS keeps it mounted. Choose based on whether a form or counter should reset when the user returns.

Data / props ↓ JavaScript expression ↓ JSX elements ↓ Visible UI
Trace the values through each step before changing the code.

Run the example

Use a separate React practice project with a Node.js version supported by Vite. Create it once with these commands, then use its development URL. Do not paste this into the Edupoly website’s own source files.

npm create vite@latest react-practice -- --template react
cd react-practice
npm install
npm run dev

Replace src/App.jsx with the following complete example. Keep Vite’s generated src/main.jsx entry point.

src/App.jsx

function PizzaCard({pizza}) {
  return <article><h2>{pizza.name}</h2><p>{pizza.vegetarian ? 'Vegetarian' : 'Non-vegetarian'}</p><p>₹{pizza.price}</p></article>;
}
export default function App() {
  const pizzas = [{id: 1, name: 'Garden', vegetarian: true, price: 180}, {id: 2, name: 'Chicken', vegetarian: false, price: 240}];
  return <main>{pizzas.filter(p => p.vegetarian).map(p => <PizzaCard key={p.id} pizza={p} />)}</main>;
}

Expected result

Only Garden appears, labelled Vegetarian with price ₹180.

Apply this to your assignments

Complete your pizza and student-card tasks, then try odd/even formatting in a child component. Test no matching records and verify the empty-state message.

Your existing examples

  • Display different elements conditionally React component
  • Conditionally apply url to image in React component

Open the Examples tab to run or inspect these supplied projects. Their original links are preserved.

Open Assignments for your complete original worksheet. Use the assignment workspace link to submit completed work.

Common mistakes

Conditions must not change the order of Hook calls. Call Hooks before conditional returns.

Check your understanding

  1. Predict the output before running the example, then compare it with the result panel.
  2. Explain which value each expression reads and which action changes it.
  3. Try the boundary cases listed in the practice task and record what you observe.
  4. Rebuild one matching assignment without copying, then compare behavior with the original example.

Reference

Official documentation for this topic · Vite setup requirements