Conditionally change the render order

I have three components <Header />

<Body />

<Footer />

. I want to change the display order according to the below condition.

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

      

or

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

      

or some other order in accordance with some new condition.

+3


source to share


3 answers


we can put the components in the array in any order we want, then we can do as shown 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>
    )
  }
}

      

0


source


Id suggest you put the order in an array

headFirst = [ Header, Body, Footer ]

      



then match them inside return

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

      

+3


source


you can make 3 variables in the 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>
)
}

      

+1


source







All Articles