Search code examples
reactjsconditional-statementscarouselreact-bootstrapternary

React conditionally returning a mapped bootstrap element based on array length


I'm creating a project page, where I'm mapping a React Bootstrap Image Carousel for each project from an array of images. That's working fine, but the problem is, if there's only one image in the array, I'd like the "next" and "previous" arrows not to appear. So I tried conditionally returning the Carousel.Item when the array length is greater than 1, and a regular image otherwise (not inside Carousel.Item tags). But because it's still within the Carousel itself, it thinks it's another Carousel slide and the arrows appear. I suspect I have the ternary statement laid out incorrectly, but every other configuration I've tried has resulted in an "Unexpected Token" error.

<Carousel>
  {imageArray.map((image, id) => { 
    return imageArray.length > 1 ?

  <Carousel.Item key={image.id}>
    <div className='project-image'>
      <img src={ image} style={{width: "80%"}} alt={title.rendered}/>
    </div>
  </Carousel.Item>
  
  :
  
  <div className='project-image'>
    <img src={ imgUrl} style={{width: "80%"}}alt={title.rendered}/>
  </div>
  })}
</Carousel>


Solution

  • You could move the ternary operator above the Carousel and return a carousel if your array is longer than one and a static image otherwise.

    In my opinion it makes more sense in general as you are currently checking the length of the array for every item iteration. However you really only need to do it once.

    Here is the updated code:

    {imageArray.length > 1 ?
      <Carousel>
         {imageArray.map((image, id) => (     
           <Carousel.Item key={image.id}>
             <div className='project-image'>
               <img src={ image} style={{width: "80%"}} alt={title.rendered}/>
             </div>
           </Carousel.Item>
         ))}
       </Carousel>
      :
      <div className='project-image'>
        <img src={ imgUrl} style={{width: "80%"}}alt={title.rendered}/>
      </div>
    }
    

    You might have to changes the styles of the .project-image div a bit to accommodate for the fact that it is no longer wrapped by a Carousel.