3

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
Bonnie
  • 611
  • 8
  • 25
blaskov
  • 56
  • 3
  • This post may help https://stackoverflow.com/questions/50009139/with-styled-components-how-to-only-apply-a-style-to-small-devices?rq=1 – Bonnie Aug 20 '19 at 20:24
  • Thanks Bonnie, it isn't what I'm looking for, but it can solve the problem. – blaskov Aug 24 '19 at 08:45
  • If you (really) want to do that, you need to keep track of the browser width yourself. For example a hook in your App component that updates a global state ( like redux ) and get that data when you need it ( in case of redux, connect ). I actually think you don't need that, also border-radius can be adjusted with media-queries – Miller Oct 02 '19 at 17:59

1 Answers1

0

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).

Rasovica
  • 239
  • 1
  • 4
  • 14