reactjs
  1. reactjs-conditional-rendering

ReactJs Conditional Rendering

Conditional rendering in React is a technique used to render a component based on certain conditions. This helps you to create more readable and maintainable code by showing different UI components based on certain conditions.

Syntax

{condition ? <Component1 /> : <Component2 />}

Example

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoggedIn: false,
    };
  }

  render() {
    const isLoggedIn = this.state.isLoggedIn;

    return (
      <div>
        {isLoggedIn ? (
          <h1>Welcome back!</h1>
        ) : (
          <button onClick={() => this.setState({ isLoggedIn: true })}>
            Login
          </button>
        )}
      </div>
    );
  }
}

export default App;

Output

Output Image

Explanation

In the above example, we have a state isLoggedIn which is false by default. Based on that state, we render either a h1 tag that says "Welcome back!" or a button that says "Login". When the button is clicked, we update the state of isLoggedIn to true and the h1 tag will render instead of the button.

Use

Conditional rendering can be used in many scenarios, such as:

  • Displaying different components for different users based on their role
  • Showing or hiding a specific component based on the user's input
  • Displaying an error message when a form is submitted incorrectly

Important Points

  • The condition must be a JavaScript expression that evaluates to a boolean value.
  • In the ternary operator, both the true and false expressions must be valid React elements.
  • You can also use logical && operator to conditionally render components.

Summary

In this article, we learned about conditional rendering in React. We went over the syntax, provided an example, explained how it works, and discussed its various uses. With conditional rendering, we can create more dynamic and interactive user interfaces.

Published on: