Files
react-test/docs/data/material/components/app-bar/BackToTop.tsx

90 lines
2.5 KiB
TypeScript
Raw Normal View History

2025-12-12 14:26:25 +09:00
import * as React from 'react';
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import CssBaseline from '@mui/material/CssBaseline';
import useScrollTrigger from '@mui/material/useScrollTrigger';
import Box from '@mui/material/Box';
import Container from '@mui/material/Container';
import Fab from '@mui/material/Fab';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
import Fade from '@mui/material/Fade';
interface Props {
/**
* Injected by the documentation to work in an iframe.
* You won't need it on your project.
*/
window?: () => Window;
children?: React.ReactElement<unknown>;
}
function ScrollTop(props: Props) {
const { children, window } = props;
// Note that you normally won't need to set the window ref as useScrollTrigger
// will default to window.
// This is only being set here because the demo is in an iframe.
const trigger = useScrollTrigger({
target: window ? window() : undefined,
disableHysteresis: true,
threshold: 100,
});
const handleClick = (event: React.MouseEvent<HTMLDivElement>) => {
const anchor = (
(event.target as HTMLDivElement).ownerDocument || document
).querySelector('#back-to-top-anchor');
if (anchor) {
anchor.scrollIntoView({
block: 'center',
});
}
};
return (
<Fade in={trigger}>
<Box
onClick={handleClick}
role="presentation"
sx={{ position: 'fixed', bottom: 16, right: 16 }}
>
{children}
</Box>
</Fade>
);
}
export default function BackToTop(props: Props) {
return (
<React.Fragment>
<CssBaseline />
<AppBar>
<Toolbar>
<Typography variant="h6" component="div">
Scroll to see button
</Typography>
</Toolbar>
</AppBar>
<Toolbar id="back-to-top-anchor" />
<Container>
<Box sx={{ my: 2 }}>
{[...new Array(12)]
.map(
() => `Cras mattis consectetur purus sit amet fermentum.
Cras justo odio, dapibus ac facilisis in, egestas eget quam.
Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
Praesent commodo cursus magna, vel scelerisque nisl consectetur et.`,
)
.join('\n')}
</Box>
</Container>
<ScrollTop {...props}>
<Fab size="small" aria-label="scroll back to top">
<KeyboardArrowUpIcon />
</Fab>
</ScrollTop>
</React.Fragment>
);
}