Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 4731

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 27, 20242024-11-27T02:43:08+00:00 2024-11-27T02:43:08+00:00

Conditional Rendering in ReactJS

  • 61k

One of the nicest thing in React is we can render components and elements conditionally.

Single Page applications are dynamic and event driven in nature. To make this possible
React has one feature called conditional rendering.

Wait what do you mean by rendering ?

By Rendering we mean to say that updating the page view based on changes in its state or props.

React components need to often display different user interface based on different conditions.

This concept is often applied in different situations:

  • Rendering external data from an API
  • Showing or hiding elements
  • Toggling application feature
  • implementing permission levels
  • Handling authentication and authorization

Lets see some ways of implementing conditional rendering in ReactJS
We have have a PackingList component rendering several Items, which can be marked as packed or not

Method 1

In Some situations we may not want to render anything at all. In that case we can return null

if (condition){     return <div>{name}<div>; } return null; 
Enter fullscreen mode Exit fullscreen mode

If condition is true, it will return JSX to render, or else it returns null
Its not common to return null from component.

// App.jsx function Item({ name, isPacked }) {   if (isPacked) {     return null;   }   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>   ); } 
Enter fullscreen mode Exit fullscreen mode

Method 2 using ternary operator ?

return (     <div>       {condition ? name + ' ✔' : name}     </div>  ) 
Enter fullscreen mode Exit fullscreen mode

In the above code if condition is true (?)
then render name + ' ✔', or else ( : ) render name

// App.jsx function Item({ name, isPacked }) {   return (     <li className="item">       {isPacked ? (         <del>           {name + ' ✔'}         </del>       ) : (         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>   ); } 
Enter fullscreen mode Exit fullscreen mode

Method 3 using Logical AND operator ( && )

return (     <div>     {name} {condition && '✔'}      </div> ) 
Enter fullscreen mode Exit fullscreen mode

JavaScript && expression returns the value of its right side
if the lift side (condition) is true. But if the condition on left side is false
the whole expression becomes false, and dosen't render anything in its place.

We shouldn't put numbers on the left
side of && .JavaScript converts the left side to a boolean automatically. However, if the left side is 0, then the whole expression gets that value (0), and React will happily render 0 rather than nothing.

// App.jsx function Item({ name, isPacked }) {   return (     <li className="item">       {name} {isPacked && '✔'}     </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>   ); } 
Enter fullscreen mode Exit fullscreen mode

Conditionally assigning JSX to a variable

The above 3 methods were shortcuts if theat becomes tricky or hard to use,
we can use if statement and a variable. You can
reassign variables defined with let

let itemContent=name; 
Enter fullscreen mode Exit fullscreen mode

Use an if statement to reassign a JSX expression to itemContent if
isPacked is true

if (isPacked) {   itemContent = name + " ✔"; } 
Enter fullscreen mode Exit fullscreen mode

Curly braces open the “window into JavaScript”.
Embed the variable with curly braces in the returned JSX tree,

<li className="item">   {itemContent} </li> 
Enter fullscreen mode Exit fullscreen mode

This style is the most verbose, but it’s also the most flexible. Here it is in action:

function Item({ name, isPacked }) {   let itemContent = name;   if (isPacked) {     itemContent = (       <del>         {name + " ✔"}       </del>     );   }   return (     <li className="item">       {itemContent}     </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>   ); } 
Enter fullscreen mode Exit fullscreen mode

Happy Coding 😎

beginnersjavascriptreactwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.