Conditional Rendering in React

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Welcome to the React documentation! This lab will give you an introduction to conditional rendering.

In React, you can conditionally render JSX using JavaScript syntax like if statements, &&, and ? : operators.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/components_props("`Components and Props`") react/FundamentalsGroup -.-> react/conditional_render("`Conditional Rendering`") subgraph Lab Skills react/jsx -.-> lab-100370{{"`Conditional Rendering in React`"}} react/components_props -.-> lab-100370{{"`Conditional Rendering in React`"}} react/conditional_render -.-> lab-100370{{"`Conditional Rendering in React`"}} end

Conditional Rendering

The React project have already been provided in the VM. In general, you only need to add code to App.js.

Please use the following command to install the dependencies:

npm i

In React, there is no special syntax for writing conditions. Instead, you’ll use the same techniques as you use when writing regular JavaScript code. For example, you can use an if statement to conditionally include JSX:

if (isPacked) {
  return <li className="item">{name} ✔</li>;
}
return <li className="item">{name}</li>;

If you prefer more compact code, you can use the conditional ? operator. Unlike if, it works inside JSX:

return <li className="item">{isPacked ? name + " ✔" : name}</li>;

When you don’t need the else branch, you can also use a shorter logical && syntax:

return <li className="item">{isPacked && name + " ✔"}</li>;

If the isPacked prop is true, this code returns a different JSX tree. With this change, some of the items get a checkmark at the end:

// App.js
function Item({ name, isPacked }) {
  if (isPacked) {
    return <li className="item">{name} ✔</li>;
  }
  return <li className="item">{name}</li>;
}

export default function PackingList() {
  return (
    <section>
      <h1>Sally Ride's Packing List</h1>
      <ul>
        <Item isPacked={true} name="Space suit" />
        <Item isPacked={true} name="Helmet with a golden leaf" />
        <Item isPacked={false} name="Photo of Tam" />
      </ul>
    </section>
  );
}

To run the project, use the following command. Then, you can refresh the Web 8080 Tab to preview the web page.

npm start

Summary

Congratulations! You have completed the Conditional Rendering lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like