I'm working on a slideshow component in React and I want the images to dynamically adjust to fit any device screen size and orientation. The goal is for the image to resize proportionally until it reaches either the top and bottom edges or left and right edges of the screen, without hiding behind a scrollbar.
Currently, the functionality of the component is not fully optimized, but you can take a look at what I have accomplished so far. However, there are some issues on mobile devices when changing orientation and zooming in/out.
As an example, I've included a similar component that handles a single image with the same styling (codesandbox)
FullscreenImage.tsx
import React from "react";
import useWindowDimensions from "./hooks/useWindowDimensions";
interface IProps {
imageUrl: string;
}
const FullscreenImage = (props: IProps) => {
const { imageUrl } = props;
const { height, width } = useWindowDimensions();
return (
<div style={{ width: width, height: height }}>
<img
style={{
height: width <= height ? "auto" : height,
width: height > width ? width : "auto",
margin: "auto",
display: "block"
}}
src={imageUrl}
alt="picsumimage"
/>
</div>
);
};
export default FullscreenImage;
useWindowDimensions.tsx
import { useState, useEffect } from "react";
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height
};
}
const useWindowDimensions = () => {
const [windowDimensions, setWindowDimensions] = useState(
getWindowDimensions()
);
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return windowDimensions;
};
export default useWindowDimensions;