React Responsive Image using same image dimensions

Size Image Container using Image Dimensions

Have you ever wondered how Facebook, LinkedIn, Reddit and Other social media websites uses this nice auto parent image resizer, that's because it helps in making there layout responsive with the image height and width.

A lot of thing can be done in JavaScript. So today we're gonna use our Image sizes to render back our image wrapper in other to fit the image properly. 


Check Out: WhatsApp Messenger Chat App with React Native.

HOW TO USE IMAGE WIDTH AND HEIGHT ON WRAPPER COMPOMENT USING REACT JS

With JavaScript we can use the Image() Global function to access our image properties and use this properties to size the image parent container through the component state. Here is the code below.

export default function ImageR({ image, type }) {

  const [imgInfo, setImgInfo] = useState({

    height: null,

    width: null,

    src: null,

  });


  useEffect(() => {

    var img = new Image();


    img.onload = function () {

      var height = img.height;

      var width = img.width;

      var src = img.src;


      setImgInfo({ height, width, src });

    };

    if (type === \"link\") {

      img.src = image;

    } else {

      img.src = image.default;

    }

  }, []);


  switch (type) {

    case \"link\":

      const { src, height, width } = imgInfo;

      return (

        <div

          className=\"pbody-img\"

          style={{

            height: height > 800 ? height * 0.8 : height,

          }}

        >

          <Img {...{ src }} />

        </div>

      );

    default:

      if (imgInfo.src) {

        const { height, width } = imgInfo;

        return (

          <div

            className=\"pbody-img\"

            style={{

              height: height > 800 ? height * 0.8 : height,

            }}

          >

            <img src={imgInfo.src} />

          </div>

        );

      }

      return null;

  }

}


Usage

<ImageInfo
           image={
              \"https://media-exp1.licdn.com/dms/image/sync/C4D27AQGREEmIz7_jxQ/articleshare-shrink_800/0?e=1605643200&v=beta&t=ufXUmuzGRJdmtcXdEfvdmxEhG5aWBSYA04MV1hCafH8\"}
            type=\"link\"

\tOR
             image={TestImg}
type=\"\"/>


With the above step we can use the image height or width on the parent container to still get an appropraite responsive layout on our web apps. Make sure to share to your friends