Material UI v5
In v5, you can use the keyframes
function (which is re-exported from emotion by default) to generate the stylesheet for keyframe:
import { styled } from '@mui/material/styles';
import { keyframes } from '@mui/system';
const spin = keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`;
const RotatedBox = styled("div")({
backgroundColor: "pink",
width: 30,
height: 30,
animation: `${spin} 1s infinite ease`
});
Because both styled
/sx
prop use emotion internally, you can pass the same style object to the sx
prop:
<Box
sx={{
backgroundColor: "pink",
width: 30,
height: 30,
animation: `${spin} 1s infinite ease`
}}
/>
Material UI v4
Just some notes on top of @Ryan's answer. If you define the keyframe
using makeStyles
. Remember to prefix the animation name with $
. I missed this small detail the first time and my code didn't work, in the example below
const useStyles = makeStyles({
"@keyframes fadeIn": {
"0%": {
opacity: 0,
transform: "translateY(5rem)"
},
"100%": {
opacity: 1,
transform: "translateY(0)"
}
},
selector: {
animation: "$fadeIn .2s ease-in-out"
}
});
Instead of
animation: "fadeIn .2s ease-in-out"
It should be
animation: "$fadeIn .2s ease-in-out"
But if you define the keyframe
in global scope. The prefix is unnecessary here
const useStyles = makeStyles({
"@global": {
"@keyframes fadeIn": {
"0%": {
opacity: 0,
transform: "translateY(5rem)"
},
"100%": {
opacity: 1,
transform: "translateY(0)"
}
}
},
selector: {
animation: "fadeIn .2s ease-in-out" // --> this works
}
});
Follow this issue on github for more discussion about this.