Mastering Conditional Rendering in React

By Published 5 min read

Mastering Conditional Rendering in React is a crucial concept in React that allows you to show or hide components or content based on certain conditions. It’s the key to building dynamic and interactive user interfaces.

Why Is Conditional Rendering Important?

Before diving into the how, let’s understand the way. Conditional rendering is vital for creating responsive and user-friendly applications. It enables your components to adapt to different scenarios, user interactions, and data conditions. With conditional rendering, you can:

  1. Display Loading Indicators: Show loading spinners or messages while waiting for data to load from an API.
  2. Handle Authentication: Render different components based on whether a user is logged in or not.
  3. Conditional Styling: Apply different styles to components depending on the state or user interactions.
  4. Error Handling: Display error messages or components when an error occurs during data fetching or form submissions.
  5. Show/Hide Elements: Conditionally show or hide elements like dropdowns, modals, or tooltips.

Using the Ternary Operator for Conditional Rendering

One of the simplest and most widely used methods for conditional rendering in React is the ternary operator. It allows you to conditionally render one component or content if a condition is true and another component or content if the condition is false.

Here’s an example of using the ternary operator for conditional rendering:

import Greeting from './Componet/Greeting';

function App() {
  const isLoggedIn = true;
  return (
    <div className="App">
      <Greeting isLoggedIn={isLoggedIn} />
    </div>
  );
}

export default App;Code language: HTML, XML (xml)
import React from 'react';

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;

  return (
    <div>
      {isLoggedIn ? (
        <p>Welcome, User!</p>
      ) : (
        <p>Please log in to continue.</p>
      )}
    </div>
  );
}

export default Greeting;Code language: HTML, XML (xml)

Output :

Mastering Conditional Example 1

In this example, the isLoggedIn prop determines whether to display a welcome message or a login prompt. The condition inside the curly braces {} is evaluated, and the appropriate content is rendered.

Using the && Operator for Conditional Rendering

The && operator is another concise way to conditionally render content in React. It works well when you want to render a component or content if a condition is true, without providing an alternative for the false condition.

Here’s how you can use the && operator:

import './App.css'

import Notification from './Componet/Notification';


function App() {

  const show = true;

  return (
    <div className="App">

      <Notification show={show}/>

    </div>
  );
}

export default App;
Code language: JavaScript (javascript)
import React from 'react';

function Notification(props) {
  const showMessage = props.show;

  return (
    <div>
      {showMessage && <p>New message received!</p>}
    </div>
  );
}

export default Notification;Code language: HTML, XML (xml)

Output :

Mastering Conditional Rendering in React example 2

In this example, the <p>New message received!</p> is only rendered if showMessage is true. If showMessage is false, nothing is rendered.

Using if Statements for Conditional Rendering

React components can also use traditional if statements to conditionally render content. This is particularly useful when you need to include more complex logic within the condition.

Here’s an example:

import './App.css'
import UserGreeting from './Componet/UserGreeting';

function App() {
  const isLoggedIn = true;

  return (
    <div className="App">

      <UserGreeting isLoggedIn = {isLoggedIn}/>

    </div>
  );
}

export default App;Code language: JavaScript (javascript)
import React from 'react';
function UserGreeting(props) {
  if (props.isLoggedIn) {
    return <p>Welcome back, User!</p>;
  }
  return <p>Please sign up or log in.</p>;
}
export default UserGreeting;Code language: HTML, XML (xml)

Output :

Example 3

In this case, an if statement is used to check if the user is logged in. If they are, a welcome message is returned; otherwise, a login prompt is returned.

Conditional Rendering with Logical OR (||) Operator

The || operator can be useful when you want to provide a default value when a certain condition is not met. It’s often used for providing fallback content when data is missing or not available.

Here’s an example:

import './App.css'
import UserProfile from './Componet/UserProfile';

function App() {

  return (
    <div className="App">
      <UserProfile name = {'John'} age={26}/>
    </div>
  );
}

export default App;Code language: JavaScript (javascript)
import React from 'react';

function UserProfile(props) {
  const { name, age } = props;

  return (
    <div>
      <p>Name: {name || 'N/A'}</p>
      <p>Age: {age || 'N/A'}</p>
    </div>
  );
}

export default UserProfile;Code language: HTML, XML (xml)

Output :

Or Condition Example 4

In this example, if the name or age props are not provided or are falsy, the default value 'N/A' is displayed.

Conditional Rendering for Lists

Conditional rendering is frequently used when dealing with lists of data. You may need to render list items based on specific conditions or filters. The map function is often used in combination with conditional rendering to achieve this.

Here’s an example of rendering a list of items based on a condition:

import './App.css'
import TaskList from './Componet/TaskList';

function App() {

  const tasks = [
    {id:1,name:'Greeting'},
    {id:2,name:'Selection'},
    {id:3,name:'Information'},
    {id:4,name:'Toure'}
  ]
  return (
    <div className="App">
      <TaskList tasks = {tasks}/>
    </div>
  );
}

export default App;
Code language: JavaScript (javascript)
import React from 'react';

function TaskList(props) {
  const tasks = props.tasks;

  return (
    <ul>
      {tasks.map((task) => {
        if (task.completed) {
          return <li key={task.id}>{task.name}</li>;
        }
        return null;
      })}
    </ul>
  );
}

export default TaskList;Code language: HTML, XML (xml)

Output :

Example 5

In this example, the map function is used to iterate through the tasks array. If a task is marked as completed, it’s rendered as a list item. If not, null is returned, effectively skipping rendering for incomplete tasks.

Best Practices for Conditional Rendering

While conditional rendering in React is flexible and versatile, it’s essential to follow best practices to maintain clean and readable code:

  1. Keep It Concise: Use the simplest method that meets your needs. For simple conditions, the ternary operator or && operator often provide clean and concise solutions.
  2. Separate Complex Logic: If your conditional rendering involves complex logic, consider moving that logic into separate functions or helper functions to keep your component code clean and understandable.
  3. Use Descriptive Variable Names: When working with conditions, use descriptive variable names to make your code more readable and self-explanatory.
  4. Avoid Excessive Nesting: Excessive nesting of conditional statements can make your code hard to read. Try to keep nesting to a minimum and consider breaking down complex conditions into smaller, more manageable parts.
  5. Document Your Code: Add comments or documentation to clarify the purpose of the conditional rendering and its expected behavior.

Conclusion

Mastering Conditional Rendering in React is a fundamental concept in React that enables you to create dynamic and responsive user interfaces. By understanding the various techniques and best practices for conditional rendering, you can build web applications that adapt to different scenarios, user interactions, and data conditions.

Whether you’re showing loading indicators, handling user authentication, or conditionally rendering lists, mastering conditional rendering is a crucial skill for React developers. It empowers you to create user-friendly, interactive, and adaptable applications that provide a great user experience.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume