Usually, we solve this problem by removing and adding a class with CSS animation attributes. How to remove animation attribute and add again quickly to trigger animation using styled-components library?
To trigger CSS animations in JavaScript, we just add the class that is set to animate the keyframes in CSS.
You can use standard CSS properties, and styled components will add vendor prefixes should they be needed. Styled components are independent of each other, and you do not have to worry about their names because the library handles that for you.
Keyframes in Styled Components. 💰 The Pragmatic Programmer: journey to mastery. 💰 One of the best books in software development, sold over 200,000 times. Styled components export a helper for dealing with CSS keyframes, which generates a uniques instance that can be used throughout the entire application.
Luckily, I learned that styled-components can incorporate animations! From the styled-components docs: CSS animations with @keyframes aren’t scoped to a single component but you still don’t want them to be global to avoid name collisions.
From the styled-components docs: CSS animations with @keyframes aren’t scoped to a single component but you still don’t want them to be global to avoid name collisions. This is why we export a keyframes helper which will generate a unique instance that you can use throughout your app
Now to incorporate the animation, import the keyframes helper from styled-components: import { keyframes } from 'styled-components'. Then it can be defined much like a component definition: Now to put it all together, we can add the animation parameters in the definition of our Circle component:
Styled components are visual primitives to style your React App and have plenty of great features, like the ability to write CSS right in the component, complexity reduction, faster loading, clear scope and other performance improvements. This article is about CSS animations with the @keyframes property.
You could use props to change the styles, for example:
const MyComp = styled.div`
transition: width 2s;
width: ${props => props.animate ? "20px" : "10px"};
`
You can then pass a prop when you use the component to trigger the animation:
<MyComp animate={booleanFlag} />
In this case, you can toggle the animate prop between true and false as necessary. Perhaps using state from the parent component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With