Is it possible to use Style System's breakpoints inside a Styled-Component?

2.6k views Asked by At

I would like to use styled-system's breakpoint and sizing mechanism inside a styled component.

Currently, I have to use 'react-media', which solves my problem, but this solution comes with a big amount of code duplication. Here is my current solution to set a StyledComponent's border-radius based on the screen size:

import React from 'react'
import styled from 'styled-components'
import theme from '../../theme'
import Media from 'react-media'

const StyledImg = styled.img`
  border-radius: ${props => (props.size / 4)};
`

function ProfileImage (props) {
  const breakpoint = theme.breakpoints[0]

  return <Media query={`(min-width: ${breakpoint})`}>
      {matches =>
        matches ? (
        <StyledImg size={props.size[1]} src={props.src} />
      ) : (
        <StyledImg size={props.size[0]} src={props.src} />
      )
    }
  </Media>
}

function ProfileCard (props) {
  return <Box bg='grey' width={1}>
    <ProfileImage width={[10, 20]} src={props.src}>
  </Box>
}

export default ProfileImage

Is it possible to get the current breakpoint index? Can I write something like this:

const StyledImg = styled.img`
  border-radius: ${props => (props.size[theme.currentBreakpointIndex] / 4)};
`

function ProfileImage (props) {
  return <StyledImg {...props} />
}

function ProfileCard (props) {
  return <Box bg='grey' width={1}>
    <ProfileImage size={[10, 20]} src={props.src}>
  </Box>
}

export default ProfileImage
1

There are 1 answers

0
Rasovica On

Reading this they suggest you inject breakpoints into queries and put them in the theme. You cant then access them like this:

styled.div`
   ${({theme: {mediaQueries: {small}}}) => small} {
       color: red;
   }
`

This solution uses css to change styles however (but in my opinion that's how it should be done).