How to add active class using React styled-components?

Sometimes, we want to add active class using React styled-components.

In this article, we’ll look at how to add active class using React styled-components.

How to add active class using React styled-components?

To add active class using React styled-components, we can add props to the component.

For instance, we write:

import React from "react";
import styled, { keyframes, css } from "styled-components";

const pulse = keyframes`
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
`;

const Button = styled.button`
  animation: ${(props) =>
    props.active
      ? css`
          ${pulse} 0.5s linear
        `
      : "none"};
`;
export default function App() {
  return (
    <>
      <Button animationLength="2s" active>
        hello
      </Button>
    </>
  );
}

We create the keyframes with the keyframes tag and a keyframe string.

Then we add the Button component with the styled.button tag.

We run the animation on the button only with the active prop is true by returning in props.active ? css ${pulse} 0.5s linear : "none" in the function.

Finally, we add the Button into App and set the animationLength and active props.

Now we should see animation in the button since we set the active prop to true.

Conclusion

To add active class using React styled-components, we can add props to the component.