Condtional Rendering

Conditional rendering in React allows you to create dynamic and interactive user interfaces by displaying different components or elements based on specific conditions. This chapter will cover everything from the basics of conditional rendering to advanced techniques, providing a comprehensive guide to mastering this essential concept. We will explore various methods for implementing conditional rendering, including if statements, ternary operators, logical AND operators, and more complex conditional structures.

Basics of Conditional Rendering

Conditional rendering in React works the same way as conditions work in JavaScript. Different techniques can be used depending on the complexity and readability of your code.

Using if Statements

You can use if statements to conditionally render a component or element.

				
					import React from 'react';

function Greeting({ isLoggedIn }) {
  if (isLoggedIn) {
    return <h1>Welcome back!</h1>;
  } else {
    return <h1>Please sign in.</h1>;
  }
}

export default Greeting;

				
			

Explanation:

  • The Greeting component receives a prop isLoggedIn.
  • It uses an if statement to check the value of isLoggedIn and returns different elements accordingly.
				
					
<h1>Welcome back!</h1>

<h1>Please sign in.</h1>

				
			

Using Ternary Operators

Ternary operators provide a concise way to handle simple conditional rendering.

				
					import React from 'react';

function Greeting({ isLoggedIn }) {
  return (
    <h1>{isLoggedIn ? 'Welcome back!' : 'Please sign in.'}</h1>
  );
}

export default Greeting;

				
			

Explanation:

  • The ternary operator checks isLoggedIn and returns one of two possible values.
				
					
<h1>Welcome back!</h1>

<h1>Please sign in.</h1>

				
			

Using Logical AND Operator (&&)

For conditions where you only need to render something when a condition is true, you can use the logical AND operator.

				
					import React from 'react';

function Mailbox({ unreadMessages }) {
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 && (
        <h2>You have {unreadMessages.length} unread messages.</h2>
      )}
    </div>
  );
}

export default Mailbox;

				
			

Explanation:

  • The logical AND operator && renders the message only if unreadMessages.length is greater than 0.
				
					<div>
  <h1>Hello!</h1>
  
  <h2>You have [number] unread messages.</h2>
</div>

				
			

Inline If-Else with Conditional Operator

Inline if-else with the conditional operator (ternary) is useful for rendering one of two components or elements based on a condition.

				
					import React from 'react';

function UserStatus({ isOnline }) {
  return (
    <div>
      {isOnline ? (
        <span className="online">Online</span>
      ) : (
        <span className="offline">Offline</span>
      )}
    </div>
  );
}

export default UserStatus;

				
			

Explanation:

  • The ternary operator renders either the span with class online or span with class offline based on isOnline.
				
					<div>
  
  <span class="online">Online</span>
  
  <span class="offline">Offline</span>
</div>

				
			

Conditional Rendering with Component Variables

You can also use variables to store elements or components before including them in the return statement.

				
					import React from 'react';

function LoginControl({ isLoggedIn }) {
  let button;

  if (isLoggedIn) {
    button = <button>Logout</button>;
  } else {
    button = <button>Login</button>;
  }

  return (
    <div>
      <h1>Login Control</h1>
      {button}
    </div>
  );
}

export default LoginControl;

				
			

Explanation:

  • The button variable stores the appropriate button element based on isLoggedIn.
				
					<div>
  <h1>Login Control</h1>
  
  <button>Logout</button>
  
  <button>Login</button>
</div>

				
			

Preventing Component Rendering

Sometimes you may want to prevent a component from rendering at all.

				
					import React from 'react';

function WarningBanner({ warn }) {
  if (!warn) {
    return null;
  }

  return (
    <div className="warning">
      Warning!
    </div>
  );
}

function Page() {
  const [showWarning, setShowWarning] = React.useState(true);

  const toggleWarning = () => {
    setShowWarning(!showWarning);
  };

  return (
    <div>
      <WarningBanner warn={showWarning} />
      <button onClick={toggleWarning}>
        {showWarning ? 'Hide' : 'Show'}
      </button>
    </div>
  );
}

export default Page;


				
			

Explanation:

  • The WarningBanner component returns null if warn is false, preventing it from rendering.
  • The Page component toggles the showWarning state, showing or hiding the WarningBanner.
				
					<div>
  
  <div class="warning">Warning!</div>
  <button>Hide</button>
  
  <button>Show</button>
</div>

				
			

Conditional Rendering in Lists

You can conditionally render elements within lists.

				
					import React from 'react';

function TodoList({ todos }) {
  return (
    <ul>
      {todos.map((todo, index) =>
        todo.completed ? null : <li key={index}>{todo.text}</li>
      )}
    </ul>
  );
}

export default TodoList;

				
			

Explanation:

  • The TodoList component maps over the todos array.
  • It renders a li element for each todo that is not completed.
				
					<ul>
  
  <li>[todo.text]</li>
</ul>


				
			

Advanced Conditional Rendering

Rendering Multiple Components

You can render different components based on multiple conditions.

				
					import React from 'react';

function AdminPanel() {
  return <h1>Admin Panel</h1>;
}

function UserPanel() {
  return <h1>User Panel</h1>;
}

function Panel({ isAdmin }) {
  return (
    <div>
      {isAdmin ? <AdminPanel /> : <UserPanel />}
    </div>
  );
}

export default Panel;

				
			

Explanation:

  • The Panel component conditionally renders either AdminPanel or UserPanel based on isAdmin.
				
					<div>
  
  <h1>Admin Panel</h1>
  
  <h1>User Panel</h1>
</div>

				
			

Conditional Rendering with Switch Cases

For more complex conditions, you can use switch cases.

				
					import React from 'react';

function Status({ status }) {
  let message;

  switch (status) {
    case 'loading':
      message = <h1>Loading...</h1>;
      break;
    case 'success':
      message = <h1>Data Loaded Successfully!</h1>;
      break;
    case 'error':
      message = <h1>Error Loading Data!</h1>;
      break;
    default:
      message = <h1>Unknown Status</h1>;
  }

  return (
    <div>
      {message}
    </div>
  );
}

export default Status;

				
			

Explanation:

  • The Status component uses a switch statement to determine which message to display based on status.
				
					<div>
  
  <h1>Loading...</h1>
  <h1>Data Loaded Successfully!</h1>
  <h1>Error Loading Data!</h1>
  <h1>Unknown Status</h1>
</div>

				
			

Practical Example 1: User Authentication

In this example, we will create a simple application that conditionally renders content based on whether a user is logged in or not. We will have a login button, a logout button, and a message that changes based on the user’s authentication status.

App component

				
					import React, { useState } from 'react';
import Greeting from './Greeting';
import AuthButton from './AuthButton';

function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  const handleLogin = () => {
    setIsLoggedIn(true);
  };

  const handleLogout = () => {
    setIsLoggedIn(false);
  };

  return (
    <div>
      <Greeting isLoggedIn={isLoggedIn} />
      <AuthButton isLoggedIn={isLoggedIn} onLogin={handleLogin} onLogout={handleLogout} />
    </div>
  );
}

export default App;

				
			

Greeting Component

				
					import React from 'react';

function Greeting({ isLoggedIn }) {
  return (
    <h1>{isLoggedIn ? 'Welcome back!' : 'Please sign in.'}</h1>
  );
}

export default Greeting;

				
			

AuthButton Component

				
					import React from 'react';

function AuthButton({ isLoggedIn, onLogin, onLogout }) {
  return (
    <button onClick={isLoggedIn ? onLogout : onLogin}>
      {isLoggedIn ? 'Logout' : 'Login'}
    </button>
  );
}

export default AuthButton;

				
			

Explanation:

  • The App component maintains the state isLoggedIn to track the user’s authentication status.
  • The Greeting component displays a message based on whether the user is logged in or not.
  • The AuthButton component renders a login button if the user is not logged in and a logout button if the user is logged in. It also handles the login and logout actions by calling the appropriate functions passed as props.
				
					
<h1>Please sign in.</h1>
<button>Login</button>

<h1>Welcome back!</h1>
<button>Logout</button>

<h1>Please sign in.</h1>
<button>Login</button>

				
			

Practical Example 2: Showing and Hiding Components

In this example, we will create an application that shows or hides additional information based on a toggle button. This will demonstrate more complex conditional rendering by controlling the visibility of a component.

App Component

				
					import React, { useState } from 'react';
import InfoToggle from './InfoToggle';

function App() {
  const [showInfo, setShowInfo] = useState(false);

  const toggleInfo = () => {
    setShowInfo(!showInfo);
  };

  return (
    <div>
      <h1>Conditional Rendering Example</h1>
      <button onClick={toggleInfo}>
        {showInfo ? 'Hide Info' : 'Show Info'}
      </button>
      {showInfo && <InfoToggle />}
    </div>
  );
}

export default App;

				
			

InfoToggle Component

				
					import React from 'react';

function InfoToggle() {
  return (
    <div>
      <h2>Additional Information</h2>
      <p>This is some extra information that can be shown or hidden by clicking the button above.</p>
    </div>
  );
}

export default InfoToggle;

				
			

Explanation:

  • The App component maintains the state showInfo to determine whether the InfoToggle component should be displayed.
  • The InfoToggle component contains the additional information that can be toggled.
  • The button in the App component toggles the showInfo state, which in turn controls the rendering of the InfoToggle component.
				
					
<h1>Conditional Rendering Example</h1>
<button>Show Info</button>

<h1>Conditional Rendering Example</h1>
<button>Hide Info</button>
<div>
  <h2>Additional Information</h2>
  <p>This is some extra information that can be shown or hidden by clicking the button above.</p>
</div>

<h1>Conditional Rendering Example</h1>
<button>Show Info</button>

				
			

Conditional rendering is a powerful feature in React that allows you to create dynamic and interactive user interfaces. By understanding and utilizing different conditional rendering techniques, such as if statements, ternary operators, logical AND operators, and switch cases, you can effectively manage the display of components and elements based on various conditions. Happy coding !❤️

Table of Contents