Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally change order of rendering React component

I have three component <Header /> <Body /> <Footer />. I want to change the order of display according to condition as below.

<div> <Header /> <Body /> <Footer /> </div>

or

<div>  <Body /> <Header /> <Footer /> </div>

or some different order according to some new condition.

like image 815
Jagajit Prusty Avatar asked Mar 22 '17 07:03

Jagajit Prusty


People also ask

How do you handle conditional rendering in React?

Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them. This example renders a different greeting depending on the value of isLoggedIn prop.

Does React render components in order?

As you know React components render in parallel. There is no guarantee in order that they finish rendering.

Which operator can be used to conditionally render a React component?

Logical && Operator Another way to conditionally render a React component is by using the && operator.

What is meant by conditional rendering in React?

In React, we can create multiple components which encapsulate behavior that we need. After that, we can render them depending on some conditions or the state of our application. In other words, based on one or several conditions, a component decides which elements it will return.


1 Answers

I'm the same case here, and I've reached to this solution, hope you find it helpful!

const Test = ({ condition }) => {
  const [first, second, third] = condition
    ? [<Header />, <Body />, <Footer />]
    : [<Footer />, <Body />, <Header />];

  return (
    <div>
      {first}
      {second}
      {third}
    </div>
  );
};

By doing this you don't have to set a key prop, and don't add any new div tag while iterating. I made an example of it with the possibility of changing the order of the items.

https://codesandbox.io/embed/pjw7kywq80

like image 146
Ema Suriano Avatar answered Sep 28 '22 04:09

Ema Suriano