Skip to main content

Delicious Reverie

blog of developer & bookworm benjamin read

Working with styled components: multiple nested properties

I've seen this fairly frequently when it comes to using shared media queries. sometimes you want to set the width of an element based on one property, but you need to access the theme too.

const StyledContainer = styled.div`
  ${(props) =>
    props.narrow
      ? css`
          @media (min-width: ${props.theme.desktopMin}) {
            max-width: 48rem;
          }
        `
      : css`
          @media (min-width: ${props.theme.desktopMin}) {
            max-width: 32rem;
          }
        `}
`;

You could destructure them like this however it can become difficult to read, particularly the position of the closing bracket, which becomes difficult to see with the template literal syntax:

const StyledContainer = styled.div`
    ${({ narrow, theme })) => narrow ? css `
        @media (min-width: ${theme.desktopMin}) {
            max-width: 48rem;
        }
      ` : css `
          @media (min-width: ${theme.desktopMin}) {
              max-width: 32rem;
          }
      `
    }
`

I think it could be better not to destructure. You could easily start to think about what would happen when you have nested ternaries, which in my time I have spent too long trying to unpick.


You're currently on the javascript disabled version of the site. To enable the site search and some pretty animations, view the javascript enabled react app.

About This Site

Delicious Reverie is the blog of developer & bookworm benjamin read. Set in Skybird and your system font. Built with Gatsby, hosted by Netlify. © Some rights are reserved. This site doesn't use any cookies or other session storage and has no tracking scripts.

Where you can find me: