New Features in Material UI Version 5
With the latest version, v5, you now have the ability to utilize the keyframes
function from emotion (re-exported by default) to create keyframe styles:
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`
});
Since both styled
and sx
prop internally use emotion, you can apply the same style object to the sx
prop as well:
<Box
sx={{
backgroundColor: "pink",
width: 30,
height: 30,
animation: `${spin} 1s infinite ease`
}}
/>
Material UI Version 4 Notes
Adding on to a previous answer, if you define the keyframe
using makeStyles
, ensure to prefix the animation name with "$". This small detail is crucial for the code to work correctly:
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"
If the keyframe
is defined in the global scope, there is no need for the prefix:
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
}
});
Stay updated with the discussion around this topic by following the relevant github issue.