Search code examples
reactjsconditional-rendering

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?


Solution

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