React Cross Fade for Material UI (MUI)

 by Robin Wieruch
 - Edit this Post

Material UI for React, also called MUI, does not come with a native CrossFade component for transitioning with a cross fade animation between two or more components. Here I want to share the cross fade component that I have used for several of my freelance projects when using Material UI:

import * as React from 'react';
import Box from '@mui/material/Box';
import Fade from '@mui/material/Fade';
type CrossFadeProps = {
components: {
in: boolean;
component: React.ReactNode;
}[];
};
const CrossFade: React.FC<CrossFadeProps> = ({ components }) => {
return (
<Box
sx={{
width: '100%',
height: '100%',
position: 'relative',
}}
>
{components.map((component, index) => (
<Fade key={index} in={component.in}>
<Box
sx={{
width: '100%',
height: '100%',
position: 'absolute',
}}
>
{component.component}
</Box>
</Fade>
))}
</Box>
);
};
export { CrossFade };

And the usage of this CrossFade component appears as follows:

<CrossFade
components={[
{
in: true,
component: <div>A</div>,
},
{
in: false,
component: <div>B</div>,
},
]}
/>

You can pass as many components as you want to the CrossFade component and depending on the in condition, which may be stateful in your implementation, it fades between these components.

Keep reading about 

Material UI for React, also called MUI, does not come with a native nested Dropdown menu. Here I want to share the nested dropdown component that I have used for several of my freelance projects when…

Material UI for React, also called MUI, does not come with a native Dropdown component. Here I want to share the dropdown component that I have used for several of my freelance projects when using…

The Road to React

Learn React by building real world applications. No setup configuration. No tooling. Plain React in 200+ pages of learning material. Learn React like 50.000+ readers.

Get it on Amazon.