React Styled-Components mobile first approach

March 10, 2020

Mobile First approach is when we start styling first for mobile before desktop or other device.

What is a typical media query?

In this case when the screen width is smaller than 768px button will be 100% width.

@media only screen and (max-width: 768px) {
  /* For mobile phones: */
  .button {
    width: 100%;
  }
}

What is a mobile first media query?

Below is a example of a mobile first media query, instead of changing the design when the width gets smaller than 768px, we set mobile styling as default and change the design when the width gets larger than 768px.

.button {
  width: 100%;
}

@media only screen and (min-width: 768px) {
  /* For mobile phones: */
  .button {
    width: 200px;
  }
}

So how do we adopt this technique with React and styled-components?

First we need to define owr breakpoints and media queries.

//media.js
import { css } from "styled-components"

const sizes = {
  uhd: 1980,
  widescreen: 1366,
  desktop: 1024,
  tablet: 768,
}
export default Object.keys(sizes).reduce((acc, label) => {
  acc[label] = (...args) => css`
    @media (min-width: ${sizes[label]}px) {
      ${css(...args)};
    }
  `
  return acc
}, {})

And then we import them every time we need to style our components.

//TitleContainer.js
import styled from "styled-components"
import media from "./media"

export const TitleContainer = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  padding: 3rem;
  ${media.desktop`
    height: 245px;
    padding: 3rem 6rem;
  `};
  ${media.widescreen`
    padding: 3rem 6rem;
    height: 345px;
  `};
`

For a complete overview of media queries take a look at the W3 media rules reference.

...