Jagajit Prusty
Jagajit Prusty

Reputation: 2110

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.

Upvotes: 9

Views: 10780

Answers (4)

Ema Suriano
Ema Suriano

Reputation: 131

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

Upvotes: 2

Jagajit Prusty
Jagajit Prusty

Reputation: 2110

we can put components in an array on whatever order we want then we can render as below.

class Layout extends React.Component {
  render() {
    let componentsOrder = [];
    componentsOrder = isEnabled('renderBottom') ? [<List />, <AddToDo />] : [<AddToDo />, <List />]
    componentsOrder = isEnabled('filter') ? [...componentsOrder, <Filter />] : [...componentsOrder]
    return (
      <div>
        {componentsOrder.map((v, i) => <div key={i}>{v}</div>)}
      </div>
    )
  }
}

Upvotes: 1

Lojka
Lojka

Reputation: 167

you can make 3 variables in render function:

render() {
let first: any = null;
let second: any = null;
let third: any = null;

if (condition) {
  first = (<Body />);
  second = (<Header />);
  third = (<Footer />);
};

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

Upvotes: 5

Rei Dien
Rei Dien

Reputation: 554

Id suggest you put the order in an array

headFirst = [ Header, Body, Footer ]

then map them inside the return

 if (headFirst) {
  return (
    <div>{
      headFirst.map(Component => (
       <Component key={ somethingunique } />
      )
    }</div>
  )
 }

Upvotes: 8

Related Questions