Conditional Rendering with JSX in React JS

Conditional rendering in React allows you to display different content based on certain conditions. In React, this is done by using JavaScript expressions inside JSX. This flexibility helps you create dynamic and interactive user interfaces. In this article, we will explore how to implement conditional rendering in React using JSX.

What is Conditional Rendering?

Conditional rendering in React refers to the ability to render different UI elements based on certain conditions or states. These conditions could be based on component state, props, or any other dynamic values. React allows you to use JavaScript's built-in control structures like if, else, and ternary operators to control which content should be rendered in the JSX.

Basic Example: Using if/else for Conditional Rendering

The simplest way to conditionally render content is by using an if/else statement, but this must be done within the component's render function, as JSX cannot directly include statements like if.

          
              function Greeting(props) {
                  if (props.isLoggedIn) {
                      return 

Welcome back!

; } else { return

Please log in.

; } }

In this example, the Greeting component checks the value of the isLoggedIn prop. If it's true, it renders a welcome message; otherwise, it prompts the user to log in.

Using Ternary Operator for Conditional Rendering

In JSX, a common approach for conditional rendering is to use the ternary operator. This is a concise way to return different values based on a condition.

          
              function Greeting(props) {
                  return 

{props.isLoggedIn ? 'Welcome back!' : 'Please log in.'}

; }

In this example, the ternary operator is used to check props.isLoggedIn. If true, it displays "Welcome back!", otherwise it shows "Please log in."

Example: Conditional Rendering in JSX with Logical &&

Another common pattern for conditional rendering in JSX is using the logical && operator. This allows you to render something only if a certain condition is true. If the condition is false, React ignores the expression and renders nothing.

          
              function Notifications(props) {
                  return (
                      
{props.messages.length > 0 &&

You have {props.messages.length} new messages.

}
); }

In this example, the Notifications component uses the && operator to check if there are any messages. If the condition is true (i.e., there are messages), it renders the <p> tag with the number of new messages. If there are no messages, nothing is rendered.

Handling Multiple Conditions

Sometimes, you need to handle more than two conditions. You can use nested ternary operators or if/else if statements to manage more complex conditions.

Example: Nested Ternary Operator

          
              function StatusMessage(props) {
                  return (
                      

{props.status === 'loading' ? 'Loading...' : props.status === 'success' ? 'Operation was successful!' : 'Something went wrong!'}

); }

This example uses a nested ternary operator to check for three possible conditions: if the status is "loading", "success", or anything else (which is considered an error state).

Example: Using if/else if/else Statements

          
              function StatusMessage(props) {
                  if (props.status === 'loading') {
                      return 

Loading...

; } else if (props.status === 'success') { return

Operation was successful!

; } else { return

Something went wrong!

; } }

In this example, we use an if/else if/else chain to check the status prop and display the appropriate message.

Rendering Lists Conditionally

Sometimes you may want to conditionally render a list of items. You can use a combination of loops and conditional checks to render elements based on their data or other criteria.

Example: Conditionally Rendering a List

          
              function TaskList(props) {
                  return (
                      
    {props.tasks.length > 0 ? ( props.tasks.map(task =>
  • {task.name}
  • ) ) : (
  • No tasks available
  • )}
); }

In this example, we check if there are any tasks in the tasks array. If there are tasks, we map over the array and render a list item for each task. If the list is empty, it renders a fallback message saying "No tasks available".

Conclusion

Conditional rendering is a powerful feature in React that allows you to create dynamic, interactive applications. Using expressions like the ternary operator, && operator, or if/else statements, you can display different content based on the component's state, props, or other conditions. By mastering conditional rendering, you can build more complex and feature-rich React applications that respond to different scenarios in real time.





Advertisement