Ensure that images in a browser maintain their proportions without distortion on all device screens and orientations by setting their height and width to match the

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;

Answer №1

if I understand correctly:

you can utilize the max-width and max-height properties like this:

<div style={{ width: desiredWidth, height: desiredHeight }}>
      <img
        style={{
          margin: "auto",
          display: "block",
          maxHeight: "100%",
          maxWidth: "100%"
        }}
        src={imageSource}
        alt="sampleImage"
      />
    </div>

https://example.com/unique-link-here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Separate .env configurations tailored for development and production environments

Managing different content in my .env files is crucial as I work with both next.js and node.js. The settings vary between development and deployment environments. During development: DOMAIN_URL=https://localhost:3000 GOOGLE_CLIENT_ID='abc' For ...

Trouble with Title Updating in Next.js and Tailwind CSS Project

I am currently facing an issue with the title of my website not updating, even though I am using next/Head and have included the title tag. "use client"; import Head from 'next/head'; import { BsFillMoonStarsFill } from 'react-ico ...

HTML5's video tags are capable of displaying video content without audio playback functionality

My current project involves importing videos using PHP, utilizing a video tag. However, I've encountered an audio issue while doing so. I've tried various codes such as: <video controls> <source src="https://www.w3schools.com/html/mov_ ...

Is there a faster way to create a typescript constructor that uses named parameters?

import { Model } from "../../../lib/db/Model"; export enum EUserRole { admin, teacher, user, } export class UserModel extends Model { name: string; phoneNo: number; role: EUserRole; createdAt: Date; constructor({ name, p ...

How Pivot Tables Function in Excel

Lately, I've been diving into the world of pivot tables in Excel and other spreadsheet programs. The idea has inspired me to consider developing a similar tool on the web platform using ReactJS. After doing some research online, I stumbled upon . Howe ...

Showcasing the selected menu item's value on an Angular button

I've encountered an issue where I have a list of menu items: <md-menu-item ng-value="menuItem.value" ng-repeat="menuItem in filtermenu.menuItems" ng-click="activeFilterCtrl.selectedfilter(menuItem)" translate> <md-button> {{ m ...

Is there a way to load all movies in advance when none of the tags are selected?

In my current project, I am working on a feature that involves an array of movie objects. Each movie has a name and tags assigned to it. I want to be able to display movies based on the tags selected by the user. For example, if the user selects the tag "c ...

Confusing Vaadin Component Styling Dilemma

I've been struggling to access the individual parts of elements that require navigating through the shadow DOM. I've been following a guide for assistance: https://github.com/vaadin/vaadin-themable-mixin/wiki/1.-Style-Scopes When I add this code ...

Modify the cursor pointer style in MUI Link using React

Is there a way to customize the cursor pointer style on MUI Link? I've tried using the 'cursor: pointer' style but it doesn't seem to work. Here is my code: <Link style={{ cursor: 'pointer' }} onClick={() => { ...

The functionality of react-waypoint's onEnter/onLeave event handlers seems to be malfunctioning

Recently, I experimented with react-waypoint to control the visibility of a div. The code works as intended by hiding the div when it reaches the waypoint inside onEnter. When the div is inside, the isInView state becomes true, which in turn triggers the d ...

The Firefox browser is not fully displaying the button background

Having an issue with a button that doesn't completely fill up on Firefox only. Here's the problem in action: This is how it should actually look: Not quite sure what to do. Here's the CSS styling being used: .button-panel .button { -web ...

Vue.js - encountering an issue with undefined response data

Greetings! I've encountered a script issue while trying to submit a form in VUE. The error message displayed in the developer panel states: "TypeError: error.response.data.errors is undefined". As a newcomer to Vue, I'm seeking some assistance as ...

Changing the size of the logo as you scroll through the page

I have implemented the following code to resize the logo as I scroll down the page. $(document).on('scroll', function() { if ($(document).scrollTop() >= 10) { $('.logo img').css('width', '50px'); } else ...

Interactive image grid with adjustable description field per image upon selection

My goal is to create a grid of images with a single text field below the grid. This text field should display the description of the image that was last clicked. The grid is implemented using floating divs within a main div, as shown in the code snippet be ...

Is it achievable to animate dynamic height using CSS? Open to JS alternatives as well

I am currently utilizing AngularJS, which enables me to utilize ng-show and ng-hide in order to display or hide elements based on a logical condition. My goal is to animate the size changes of the container when the child objects are shown or hidden, creat ...

Issue: ray.intersectScene does not exist as a function

For my basic WebGL project, I have been utilizing the sim.js code and its components. Recently, when I attempted to use the frustum class (refer to this question), it required updating my three.js. Unfortunately, this caused an issue: TypeError: ray.inter ...

Is it possible to integrate the Firestore npm library into my Express application?

Recently, I created my own library to act as a nosql database on my node.js web server in place of mongodb. I came across this interesting quote: Applications that use Google's Server SDKs should not be used in end-user environments, such as on pho ...

The Autocomplete field's label remains visible even after the form is submitted

I am currently developing a feature that allows users to select an option in the Autocomplete component. In the parent component, I pass these props: const filterDropdownConfig: FilterSelectAutocomplete = { data: scenariosList, label: { className: &apos ...

Image Blob increases over 50 times its original size when uploaded

I'm completely baffled by the situation unfolding here. Using Preprocess.js, I am resizing/compressing an image on the front-end. During the processfile() function on the image.onload (line 32), I convert the toDataURL() string to a Blob, in order to ...

Guide to implementing a DataTable in MVC4 UI using jQuery

Looking to set up a DataTable using jQuery similar to the one shown in this image: https://i.stack.imgur.com/DNUcd.png I'm not very comfortable with jQuery, so please be patient and avoid asking me what I've tried. I don't know how to stru ...