4

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>
  );

2 Answers 2

3

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>
);
Sign up to request clarification or add additional context in comments.

Comments

0

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()}
   )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.