I need to have a vertically centered Box with content inside, and then an optional second Box underneath. When the second box is shown, the position of the first box should not change – to clarify, the position of the first box must always be in the direct center of the viewport.
The ideal solution will solely use flexbox, without relying on things like absolute/fixed positioning, etc.
Some code:
import { useState } from "react";
import Container from "@mui/material/Container";
import MuiBox from "@mui/material/Box";
import Button from "@mui/material/Button";
const Box = (props) => (
<MuiBox sx={{ outline: "1px red solid" }} {...props}>
{props.children}
</MuiBox>
);
export default function App() {
const [secondShown, setSecondShown] = useState(false);
const toggleShown = () => setSecondShown(!secondShown);
return (
<Container>
<Box
id="outer-container"
sx={{
py: 2,
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
height: "100dvh",
}}
>
<Box id="container">
<Box id="first" sx={{ p: 2 }}>
<Box>first box - should always stay in the vertical center</Box>
<Button onClick={toggleShown} variant="outlined">
toggle 2nd box
</Button>
</Box>
{secondShown && (
<Box id="second" sx={{ p: 2 }}>
second box - should render without pushing the first box up
</Box>
)}
</Box>
</Box>
</Container>
);
}