Portal
The portal component renders its children into a new "subtree" outside of current DOM hierarchy.
The children of the portal component will be appended to the
container
specified. The component is used internally by the Modal
and Popper
components.Example
It looks like I will render here.
import * as React from 'react'; import Box from '@mui/material/Box'; import Portal from '@mui/material/Portal'; export default function SimplePortal() { const [show, setShow] = React.useState(false); const container = React.useRef(null); const handleClick = () => { setShow(!show); }; return ( <div> <button type="button" onClick={handleClick}> {show ? 'Unmount children' : 'Mount children'} </button> <Box sx={{ p: 1, my: 1, border: '1px solid' }}> It looks like I will render here. {show ? ( <Portal container={container.current}> <span>But I actually render here!</span> </Portal> ) : null} </Box> <Box sx={{ p: 1, my: 1, border: '1px solid' }} ref={container} /> </div> ); }
Server-side
React doesn't support the
createPortal()
API on the server. You have to wait for the client-side hydration to see the children.Unstyled
As the component does not have any styles, it also comes with the Base package.
import Portal from '@mui/base/Portal';