React Basics Conditional rendering

Conditional rendering is a common technique in React for displaying different content based on certain conditions. You can use conditional rendering to show or hide elements, render different components, or change the appearance of a component based on its state.

One way to implement conditional rendering in React is by using the ternary operator. Here’s an example of how to render different content based on a boolean value:

jsx
class Greeting extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isLoggedIn: false };
  }

  render() {
    return (
{this.state.isLoggedIn ? (Welcome back!

) : ( )}

    );
  }
}

In this example, we’re defining a `Greeting` component with an initial state of `{ isLoggedIn: false }`. We’re then using the ternary operator to render either a `

` element that says “Welcome back!” if the user is logged in, or a `

Another way to implement conditional rendering in React is by using the `&&` operator. Here’s an example of how to render an element only if a certain condition is true:

jsx
class Alert extends React.Component {
  constructor(props) {
    super(props);
    this.state = { showAlert: true };
  }

  render() {
    return (
{this.state.showAlert &&Alert: {this.props.message}

}

    );
  }
}

In this example, we’re defining an `Alert` component with an initial state of `{ showAlert: true }`. We’re then using the `&&` operator to render a `

` element with the `message` prop only if `showAlert` is true.

You can also use conditional rendering to render different components based on a condition. Here’s an example of how to render either a `Login` component or a `Logout` component based on the user’s login status:

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

  render() {
    return (
{this.state.isLoggedIn ? : }
    );
  }
}

In this example, we’re defining an `App` component with an initial state of `{ isLoggedIn: false }`. We’re then using conditional rendering to render either a `Logout` component if the user is logged in, or a `Login` component if the user is not logged in.

Overall, conditional rendering is a powerful technique in React that allows you to create dynamic and flexible user interfaces. By using conditional rendering, you can build components that respond to user input and update in real-time.