Skip to content

Instantly share code, notes, and snippets.

@IvanAdmaers
Last active March 8, 2022 06:52
Show Gist options
  • Save IvanAdmaers/6414cbc0e99bbd171881b236f996c982 to your computer and use it in GitHub Desktop.
Save IvanAdmaers/6414cbc0e99bbd171881b236f996c982 to your computer and use it in GitHub Desktop.
PreviewImage | NextJS, MUI 5
import PropTypes from 'prop-types';
import Link from 'next/link';
import { Box } from '@mui/material';
/**
* @returns {number} - Image padding bottom
*/
const getImagePaddingBottom = (width = 0, height = 0) => 100 * (height / width);
const PreviewImage = ({ link, src, width, height, alt }) => {
const paddingBottom = getImagePaddingBottom(width, height);
const imageMaxHeight = 512;
const maxHeight = height > imageMaxHeight ? imageMaxHeight : height;
return (
<Box
sx={{
position: 'relative',
maxHeight,
}}
>
<Box
sx={{
paddingBottom: `${paddingBottom}%`,
}}
>
<Box
sx={{
position: 'absolute',
inset: 0,
}}
>
<Link href={link}>
<Box
sx={{
maxHeight: imageMaxHeight,
margin: '0 auto',
display: 'flex',
justifyContent: 'center',
}}
>
<Box
component="img"
src={src}
alt={alt}
sx={{
display: 'block',
maxWidth: '100%',
maxHeight: imageMaxHeight,
}}
/>
</Box>
</Link>
</Box>
</Box>
</Box>
);
};
PreviewImage.propTypes = {
link: PropTypes.string.isRequired,
src: PropTypes.string.isRequired,
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
alt: PropTypes.string.isRequired,
};
export default PreviewImage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment