Sometimes, we want to add transitions to React styled components with JavaScript.
In this article, we’ll look at how to add transitions to React styled components with JavaScript.
How to add transitions to React styled components with JavaScript?
To add transitions to React styled components with JavaScript, we can change styles according to props.
For instance, we write:
import React from "react";
import styled, { css } from "styled-components";
const Button = styled.div`
transform: rotate(0deg);
transition: transform 0.2s ease-out;
background: green;
width: 50px;
${(props) =>
props.expanded &&
css`
transform: rotate(45deg);
`};
`;
export default function App() {
const [expanded, setExpanded] = React.useState();
React.useEffect(() => {
setTimeout(() => {
setExpanded(true);
}, 2000);
}, []);
return <Button expanded={expanded}>hello</Button>;
}
to create a styled div and assign it to Button
.
In it, we set the transform
property to rotate the div according to the value of the expanded
prop.
Then in App
, we have the expanded
state that’s set as the value of the expanded
prop.
And we call setExpanded
in the setTimeout
callback 2 seconds after App
is mounted.
Conclusion
To add transitions to React styled components with JavaScript, we can change styles according to props.