javascriptreactjsnext.js13

How to Identify a image is portrait or landscape image in react js?


how to dynamically identify whether an image is in portrait or landscape orientation using React.js. This guide explains the steps to analyze image dimensions and apply conditional styling to ensure your application adapts seamlessly to varying image formats.

I attempted to calculate the image's width and height using React.js and conditionally applied styles based on the orientation (portrait or landscape). I expected the component to accurately detect the image orientation and dynamically adjust the styling to fit the layout requirements.


Solution

  • <Image
      src={img.png}
      onLoad={(event) => {
        const imgElement = event.target as HTMLImageElement;
        const isPortrait = imgElement.naturalHeight > imgElement.naturalWidth;
        if (isPortrait) {
          imgElement.style.objectFit = 'cover'
        } else {
          imgElement.style.objectFit = 'contain'
        }
      }}
    />
    

    In an image element, you can use the onload property to check if the naturalHeight is greater than the naturalWidth. Based on this condition, you can dynamically change the style, ensuring the layout adapts appropriately.