How to use Media Queries inside a React Styled Components Keyframe?

damon picture damon · Aug 20, 2019 · Viewed 10.7k times · Source

I can get media queries to work properly inside a regular styled-components component however when I attempted to use it in a keyframe (via import from styled-components) it does not seem to work at all.

Attempting to get a div to animate to a specific position, but have that end position change when the window is < 800px, I've attempted this:

import styled, { keyframes } from 'styled-components';

// ... further down ...

const slideAnim = keyframes`
  100% {
    top: 20px;
    left: 30px;
  }

  @media (max-width: 800px) {
    top: 70px;
    left: 50px;
    }

`;

I have also tried putting the media query in the 100% block:

const slideAnim = keyframes`
  100% {
    top: 20px;
    left: 30px;

    @media (max-width: 800px) {
       top: 70px;
       left: 50px;
    }
  }
`;

I made a helpful interactive demonstration of what I am trying to achieve (problem code is at line 24): https://codesandbox.io/embed/fragrant-star-m71ct

Feel free to change the breakpoint variable from 800 if you need to.

Any help is appreciated!

Answer

Dacre Denny picture Dacre Denny · Aug 20, 2019

You could take a different approach, where your keyframes animation is instead defined as a function like this:

const slideAnim = (top, left) => keyframes`
  100% {
    top: ${ top };
    left: ${ left };
  }  
`;

The function accepts input parameters that dictate the destination coordinates of top and left for that animation's final keyframe.

In your stlyed component (ie Box1), you'd then invoke slideAnim() with specific coordinates to each breakpoint, to achieve different animation behavior per breakpoint:

/*
Declare responsive styling in the Box1 component, where destination
coordinates are specified for the animate on a per-breakpoint-basis
*/
const Box1 = styled.div`
  width: 20px;
  height: 20px;
  background-color: blue;
  position: absolute;
  left: -100px;
  top: 80px;

  &.slide {

    animation: ${slideAnim('20px', '30px')} 0.4s ease-in-out forwards;

    @media (max-width: ${breakpoint}px) {
      animation: ${slideAnim('70px', '50px')} 0.4s ease-in-out forwards;
    }    
  }
`;

In summary, the idea is to shift the responsive styling into your styled component (ie Box1), while defining a reusable function that contains the common/shared keyframes for each responsive breakpoint.

Here's a working example - hope that helps!