JSFiddle - React, Tailwind, and code Playground

HTML

<img src="https://placeimg.com/640/480/animals" id="image1" />

<img src="https://placeimg.com/480/640/animals" id="image2" />

CSS

img {
  width: 200px;
  height: 200px;
  object-fit: contain;
  border: 1px solid red;
}

JavaScript

function getContainedSize(img) {
  var ratio = img.naturalWidth/img.naturalHeight
  var width = img.height*ratio
  var height = img.height
  if (width > img.width) {
  	width = img.width
    height = img.width/ratio
  }
  return [width, height]
}

document.getElementById('image1').addEventListener('load', function(e) {
  console.log('image1', getContainedSize(e.target))
});
document.getElementById('image2').addEventListener('load', function(e) {
  console.log('image2', getContainedSize(e.target))
});