홍우지
홍우지

Reputation: 385

React Conditional Render with object mapping and extra components

I want to do conditional rendering with mapping Object and component together

For example

return(
    fixed? 
      Object.values(data).map((content, index)=>(
       <SomeObject1/> 
      )
      // mapping and extra components
       <ExtraThing1/>
       <ExtraThing2/>
      :

        Object.values(data).map((content, index)=>(
       <SomeObject2/> 
      )
       <ExtraThing3/>
       <ExtraThing4/>

)

Is there way to do this in one return?

Upvotes: 1

Views: 648

Answers (1)

Drew Reese
Drew Reese

Reputation: 203099

I think @Yoshi's answer is technically correct, but doesn't quite match OP's code. The React Fragment (<></>) grouping is on each branch of the ternary operator, each group consisting of the mapped components and some extra components. For each returned value a single React node should be returned.

return fixed ? (
  <>
    {Object.values(data).map((content, index) => (
      <SomeObject1 />
    ))}
    // mapping and extra components
    <ExtraThing1 />
    <ExtraThing2 />
  </>
) : (
  <>
    {Object.values(data).map((content, index) => (
      <SomeObject2 />
    ))}
    <ExtraThing3 />
    <ExtraThing4 />
  </>
);

Upvotes: 2

Related Questions