Search code examples
reactjsiterationstyled-components

React and Styled Component - conditional styling based on current iteration


I'm trying to style images in my gallery based on properties that each image have. So far I found that this is working:

const ImageContainer = styled.div`
  display: flex;
`

function Gallery({gallery}) {
  return (
    {gallery.map(image => {
      return (
        <ImageContainer 
          key={image.id} 
          style={{backgroundColor: (image.height > image.width) ? 'red' : 'blue'}}
        >
          <img src={image.thumb} alt="puppy" />
        </ImageContainer>
      )
    })}
  )
}

but I'm looking for something cleaner, like:

const ImageContainer = styled.div`
  display: flex;
  background-color: ${(image.height > image.width) ? 'red' : 'blue'}
`

function Gallery({gallery}) {
  return (
    {gallery.map(image => {
      return (
        <ImageContainer key={image.id}>
          <img src={image.thumb} alt="puppy" />
        </ImageContainer>
      )
    })}
  )
}

Is it possible?


Solution

  • Yes, it is possible. You need to pass height and width as props to the styled component -

    const ImageContainer = styled.div`
      display: flex;
      background-color: ${({ height, width }) => (height > width) ? 'red' : 'blue'}
    `
    
    function Gallery({gallery}) {
      return (
        {gallery.map(image => {
          return (
            <ImageContainer key={image.id} height={image.height} width={image.width}>
              <img src={image.thumb} alt="puppy" />
            </ImageContainer>
          )
        })}
      )
    }
    

    You can find more information about passed props in styled-components right here.