How to implement conditional rendering in React?

Member

by rollin , in category: Javascript , 3 months ago

How to implement conditional rendering in React?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , 3 months ago

@rollin 

Conditional rendering in React can be implemented using various techniques. Here are a few examples:

  1. Using if-else statements:
1
2
3
4
5
6
7
render() {
  if (condition) {
    return <Component1 />;
  } else {
    return <Component2 />;
  }
}


  1. Using the ternary operator:
1
2
3
4
5
6
7
render() {
  return (
    <div>
      {condition ? <Component1 /> : <Component2 />}
    </div>
  );
}


  1. Using logical && operator:
1
2
3
4
5
6
7
render() {
  return (
    <div>
      {condition && <Component1 />}
    </div>
  );
}


  1. Using a separate function:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
renderComponent() {
  if (condition) {
    return <Component1 />;
  } else {
    return <Component2 />;
  }
}

render() {
  return (
    <div>
      {this.renderComponent()}
    </div>
  );
}


It's important to note that the condition in all these examples can be any JavaScript expression that evaluates to a boolean value.