Conditional Rendering in React

Job-ready Online Courses: Click, Learn, Succeed, Start Now!

Conditional rendering in React allows you to conditionally render elements based on certain conditions. This means that you can choose to render elements or not based on certain variables, such as the value of a component’s state or the presence of data in an array. Conditional rendering is a powerful tool for creating dynamic and engaging user interfaces, and is essential for building complex React applications.

If-else condition in React

In JavaScript, you can use conditional operators to write concise, one-line expressions that perform simple tests and return a value based on the result of the test. When combined with the ternary operator, ?, and the logical OR operator, ||, you can create conditional expressions that mimic the behavior of if-else statements. Here’s an example:

const age = 20;
const message = age >= 18 ? 'You are an adult' : 'You are a minor';
console.log(message); 

Output:

You are an adult

In the above code, we have a variable age set to 18, and we’re using the conditional operator to check if age is greater than or equal to 18. If the condition is true, the expression before the : is returned, which in this case is the string ‘You are an adult’. If the condition is false, the expression after the : is returned, which in this case is the string ‘You are a minor’. The resulting value is assigned to the variable message, which we then log to the console.

By using conditional operators in this way, we can write concise, easy-to-read expressions that perform simple tests and return a value based on the result of the test, without having to write out if-else statements. However, it’s important to note that this approach is only suitable for simple tests and expressions. For more complex logic, if-else statements may be more appropriate.

React Ternary Operator

One of the most common ways to conditionally render elements in React is through the use of the ternary operator. The ternary operator is a shorthand way of writing an if statement, and it can be used within JSX to conditionally render elements. The syntax for using the ternary operator within JSX looks like this:

function ExampleComponent(props) {
  const isTrue = props.isTrue;

  return (
    <div>
      {isTrue ? <p>True</p> : <p>False</p>}
    </div>
  );
}

ReactDOM.render(<ExampleComponent isTrue={true} />, document.getElementById('root'));

Output:

True

In this example, the ternary operator checks the value of condition. If condition is true, the component will render the <p>True</p> element, and if condition is false, the component will render the <p>False</p> element.

React && Operator

Another common way to conditionally render elements in React is through the use of the && operator. The && operator allows you to conditionally render elements based on the truthiness of an expression. If the expression is truthy, the elements will be rendered, and if the expression is falsy, the elements will not be rendered. The syntax for using the && operator within JSX looks like this:

function ExampleComponent(props) {
  const isTrue = props.isTrue;

  return (
    <div>
      {isTrue && <p>True</p>}
    </div>
  );
}

ReactDOM.render(<ExampleComponent isTrue={true} />, document.getElementById('root'));

Output:

True

In this example, the && operator checks the value of condition. If condition is truthy, the component will render the <p>True</p> element, and if condition is falsy, the component will not render any elements.

React Conditional Rendering with Functions:

In addition to using the ternary operator and the && operator, you can also use functions to conditionally render elements in React. The idea is to define a function that returns JSX based on a certain condition, and then call that function within your component’s render method. The syntax for using a function to conditionally render elements looks like this:

function User(props) {
  return <h1>Welcome to DataFlair</h1>;
}

function Guest(props) {
  return <h1>Please sign up.</h1>;
}

function Login(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <User />;
  }
  return <Guest />;
}

const root = ReactDOM.createRoot(document.getElementById('root')); 
root.render(<Login isLoggedIn={true} />);

Output:

Welcome to DataFlair

Example:

function User(props) {
  return <h1>Welcome to DataFlair</h1>;
}

function Guest(props) {
  return <h1>Please sign up.</h1>;
}

function Login(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <User />;
  }
  return <Guest />;
}

const root = ReactDOM.createRoot(document.getElementById('root')); 
root.render(<Login isLoggedIn={false} />);

Output:

Please sign up.

In this example, the renderElement function checks the value of condition and returns the appropriate JSX based on the result. The render method then calls the renderElement function, which returns the JSX to be rendered by the component.

In the first code, the isLoggedIn is marked as True, and in the second code it is marked as false, and we can see the difference between the output generated based on the values.

Using Element Variables with react conditionals

In React, you can use element variables to conditionally render elements based on the result of a test. An element variable is simply a variable that holds a React element, which can then be rendered using JSX. Here’s an example:

import React from 'react';

function ExampleComponent(props) {
  const isLoggedin = props.isLoggedin;

  let message;
  if (isLoggedin) {
    message = <h1>Welcome back!</h1>;
  } else {
    message = <h1>Please log in.</h1>;
  }

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

export default ExampleComponent;

Output:

Welcome back!

In the above code, we’re using an element variable called message to conditionally render a message based on whether the user is logged in or not. We first define a variable isLoggedin that is passed in as a prop. We then create the message variable and use an if-else statement to assign it the appropriate value based on the value of isLoggedin. Finally, we render the message variable using JSX.

Using element variables with conditionals can help make your code more readable and maintainable, especially when dealing with complex conditionals. It allows you to break down the rendering logic into smaller, more manageable pieces, and makes it easier to reason about what’s happening in your code.

Conclusion:

Conditional rendering in React is a powerful tool for creating dynamic and engaging user interfaces. By using the ternary operator, the && operator, or functions, you can choose to render elements based on certain conditions, allowing you to create complex and dynamic applications. Understanding the syntax and behavior of conditional rendering is essential for building effective React applications, and mastering these skills will help you take your React development to the next level.

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *