PineCone
PineCone

Reputation: 2343

Include multiple components and <div> in if statement in React

I am trying to include multiple componentsand <div> in React under one ´if´ statement. Since React only returns one element it requires all components and/or <div> elements to be wrapped in one root <div> element. Tried but still couldn't manage.

I need to have <Divider> component and <div className="prod-flow"> inside the the conditional statement. This means I need to hide the entire block if the condition is false. Currently <Divider> component can't be hidden since it's outside the if statement. Don't want to use same condition twice to validate.

Tried : Wrapping all the elements with one <div> - didn't work. Wrapping the entire block with [] inside {} - didn't work.

        <Divider text="PRODABC" className="blue" />
        <div className="prod-flow">
           {supplyProducts(this.state.products).length > 0 &&
             <FlowSettings
               flow={this.state.room.attributes.flow}
               products={supplyProducts(this.state.products)}
               setpointChange={this.handleSetpointChange}
               sumChange={this.handleSumChange} />
           }
        </div>

Need: Something like

return(
   <div>
     <Component1 />
     <div>
     ...
     ...
     </div>

     {supplyProducts(this.state.products).length > 0 &&
     ...
     ... //<Component2 />
     ... //<div>
          //<Component3 />
     ... //</div>
     }
  </div>
  );

Upvotes: 3

Views: 2878

Answers (2)

Elumalai Kaliyaperumal
Elumalai Kaliyaperumal

Reputation: 1520

Put wrapper on conditional render!

return(
   <div>
     <Component1 />
     <div>...</div>
     {supplyProducts(this.state.products).length > 0 &&
       <div> //Wrapper here
         <Component2 />
         <div>...</div>
         <Component3 />
         <div>...</div>
       </div>
     }
  </div>
);

Upvotes: 2

Adeel Imran
Adeel Imran

Reputation: 13966

in your render method do something like this.

render () {

   const renderMore = () => (
       <div>
         <Component1/>
         <div></div>
         <Component2/>
       </div>
   );

   return () (
       <div>
       <Component1 />
       <div>
       ...
       ...
       </div>
      {supplyProducts(this.state.products).length > 0 && renderMore()}
   )
}

Upvotes: 0

Related Questions