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.
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.
As you know React components render in parallel. There is no guarantee in order that they finish rendering.
Logical && Operator Another way to conditionally render a React component is by using the && operator.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With