Solution

To use keyframes in styled components, we have use slide keyframes and MovingButton.

Snippet

In this snippet, we will see how to use keyframes in styled components and slide animation at three different points during the animation. First-line animation defines 0% transform and second-line animation defines 50% transform and third-line animation defines 100% transform.

 const slide = keyframes`
  0% { transform: translateX(0) }
  50% { transform: translateX(150%) }
  100% { transform: translateX(0) }
`;

Example

In this example, we will create styled components as the animation button and we will pass slide animation as defined using a keyframes block.

Let’s start coding…

App.js

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

const slide = keyframes`
  0% { transform: translateX(0) }
  50% { transform: translateX(150%) }
  100% { transform: translateX(0) }
`;

const MovingButton = styled.button`
  margin: 20px;
  padding: 10px;
  background: #cfgvde;
  border: 2px solid red;
  border-radius: 4px;
  animation: ${slide} 2s ease-in-out infinite;
`;

const Example12 = () => {
  return <MovingButton>I'm moving</MovingButton>;
};

export default Example12;

Output

add element, array

codesandbox