I have a hero with multiple images, I want to display images according to screen sizes, for example, if the user is using a big screen, the hero will load the large/wide images, and if he uses a phone, the hero will display a different image that is not wide to fit the screen. I do not know how to do this with nextjs, there is no way to specify which image to load on a different screen.
CodePudding user response:
This is tailwind/next example
<div className="lg:absolute lg:inset-y-0 lg:right-0 lg:w-1/2">
<Image
className="h-56 w-full object-cover sm:h-72 md:h-96 lg:w-full lg:h-full"
src={image}
alt={title}
// this is deprecated in next 13, just use "fill" as prop
layout="fill"
/>
</div>
fill:
A boolean that causes the image to fill the parent element instead of setting width and height.
The parent element must assign position: "relative", position: "fixed", or position: "absolute" style.
By default, the img element will automatically be assigned the position: "absolute" style.
If you want to detect size and based on size you want to use different images, you can use react-resize-detector npm package.
import { useResizeDetector } from 'react-resize-detector';
const CustomComponent = () => {
const { width, height, ref } = useResizeDetector();
return <div ref={ref}>{`${width}x${height}`}</div>;
};
Once you detect the size, you can write a logic to decide which image to use
CodePudding user response:
I did solve the problem using nextjs's useMediaQuery { const mobile = useMediaQuery(theme.breakpoints.down('sm')); }, but the results aren't perfect, because if you use mobile ? [....] : [....] you cannot add 'priority' to the image components, if you try to add it, it will load both images first, then execute the conditional statement to hide one. so you have to sacrifice that.