adjusting array based on screen size fluctuations

Imagine having two arrays of images named landscape_images[] and portrait_images[]. One is for the landscape view and the other for the portrait view. When the screen width is in landscape mode, the wide resolution images will be displayed on the body. Conversely, when the screen is in portrait mode, the long-sized images will be displayed. Each array consists of a list of objects that contain the source path of the image. How can this be achieved using React, CSS, JavaScript, and HTML?

Answer №1

One way to determine the orientation of a device is by using window.matchMedia, which closely resembles CSS and is my preferred method.


if (window.matchMedia("(orientation: portrait)").matches) {
   // This means you are in PORTRAIT mode
}

if (window.matchMedia("(orientation: landscape)").matches) {
   // This means you are in LANDSCAPE mode
}

Alternatively, you can check if the window height is greater than the width:
if(window.innerHeight > window.innerWidth){
    alert("Please switch to Landscape mode!");
}

Answer №2

If you want to achieve the same effect using only CSS, consider this approach:

body {  
    background-image: url("image.jpg");   
}

@media (max-width: 600px) {
    body {
        background-image: url("image.jpg");
    }
}

Answer №3

import { useLayoutEffect, useState } from "react";
import "./styles.css";
//arrays for different image orientations
const array1 = ["portrait iamge 1","portrait image 2"]
const array2 = ["landscape image 2","landscape image2"]

export default function App() {
  const [displayType, setDisplayType] = useState("portrait")
  const portraitThreshold = 700 // threshold for portrait orientation

  useLayoutEffect(()=>{
  
    const checkWindowSize = ()=>{
      if(window.innerWidth > portraitThreshold)
        setDisplayType("landscape")
      else 
        setDisplayType("portrait")
    }

    window.addEventListener("resize", checkWindowSize)
    return ()=>window.removeEventListener("resize", checkWindowSize)
  },[])

  
  return (
    <div className="App">
      {displayType === "portrait"?array1:array2}
    </div>
  );
}

This code tracks the window size and sets display type based on it using useLayoutEffect.

The images are displayed according to the selected orientation.

Visit this sandbox to test it out!

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

Locate the initial div with a distinct class from the bottom upwards

If I have a HTML page and want to search for the last occurrence of a div with a specific class, how can I do that using Jquery? Assuming the following HTML structure: <div class="container"> <div id="1" class="something special"></div& ...

Ensure that the radio is turned on by clicking the button or selecting the radio option

Is it possible to create a radio button within a button using mui, where the user can click on either the radio button or the button to check it? The user should only be able to choose one option - either female or male. Instead of using multiple use stat ...

Using JSON in Node.js

After recently diving into Node, I've been working on parsing JSON data from an API. While I have managed to access most of the JSON content, there are certain elements that seem to elude me. var request = require("request"); var url = 'https: ...

The state value in React useContext remains unchanged when navigating between pages

Currently, I am delving into the useContext hook and experimenting with a shopping cart exercise in Next.js with app router. This exercise involves managing the cart's value globally. However, I encountered an issue when trying to pass the updated ca ...

Organize all ngDialog instances within a factory and access them through a directive

In order to keep the ngDialogs centralized in one place instead of dispersed, I had the idea of creating a factory named modal.js. This factory would contain a list of all the modals with a switch statement. Here is an example: .factory(&ap ...

Tips for Viewing React.js Pages on Your Web Browser

Perhaps this question may sound silly, but as a React beginner, I have been using CDN Links and the "npx create-react-app" functions to build apps. Now, I have some supporting files for a book I am reading, and I want to view the chapters in a w ...

Ensure that the div automatically scrolls to the bottom when it is loaded, and also when new data is added - using angular

My goal is to replicate the functionality of the iPhone's "Messages" app on a web application using AngularJS or any other JavaScript framework. Each message will be contained in a div element within a larger container. When a new message is added, I ...

Issue encountered while accessing theme properties in a ReactJs component with Typescript

I am trying to pass the color of a theme to a component in my TypeScript project (as a beginner). However, I have encountered an error that I am struggling to resolve. The specific error message reads: 'Parameter 'props' implicitly has an ...

PHP: Dynamically adjust image size from database to fit different screen sizes

Managing a website with various categories means each category has its own assigned image stored in the database. So, when a product from a specific category like bikes or chairs is displayed on the website, the corresponding image needs to be retrieved an ...

Organize data in a Vue.js table

Currently facing an issue with sorting my table in vue.js. Looking to organize the table so that campaigns with the highest spend are displayed at the top in descending order. Here is the code I'm working with: <template> <div class=" ...

Is using display:table an effective approach for achieving equal height columns?

I am currently working on a responsive design project and I need two columns of equal height. I do not want to rely on JavaScript for this, and I prefer having some whitespace between the columns to enhance readability. I have tried two different layouts; ...

Record the success or failure of a Protractor test case to generate customized reports

Recently, I implemented Protractor testing for our Angular apps at the company and I've been searching for a straightforward method to record the pass/fail status of each scenario in the spec classes. Is there a simple solution for this? Despite my at ...

React-router-sitemap lacks a definition for 'Require'

According to the official documentation here, this is how the sitemap-builder.js file should be structured: require('babel-register'); const router = require('./router').default; const Sitemap = require('../').default; ( ...

The 404 error is handled by the express application before continuing to other routes. Some routes may not be recognized by the express.Router module

Shown below is the content of app.js: var express = require('express'); var routes = require('./routes/index'); app = express(); app.use('/', routes); // catch 404 and forward to error handler app.use(function(req, res, next ...

There are no elements displayed beneath the div

If you're short on time, let me explain my point with an image: Here is the HTML code I am working with: <div align="center"> <div class="img-container"> <div class="myconatiner"> <h2>Headline< ...

Retrieve events triggered by each element

Currently, my research centers around digital marketing and user experience. In order to gather the necessary data for this study, I must collect event logs from all components within a UI to create datasets on usability patterns. In a web interface, such ...

What is the best way to ensure the width of the div is adjusted to fit the table it contains?

What is the best way to adjust the width of a div containing a potentially wider-than-screen table? Despite setting padding: 10px for the div, the right padding disappears when the table exceeds the screen width. Below is an example code snippet: <div ...

Continuously looping through the function based on availability in Symbol ES6

When using the ES6 Symbols iterator, I found that I needed to call the next function each time to print the next item during iteration. Below is the code snippet: var title = "Omkar"; var iterateIt = console.log(typeof title[Symbol.iterator]); var iter ...

The 'this' variable is malfunctioning when trying to assign a JSONP array to an AngularJS controller

I'm working with a REST service in my angular controller and using JSONP to make the call. I need to store the array that is returned from the service into a variable. This is what I currently have: this.testTheRest = function() { $http.jsonp(&a ...

The function Document.getElementsByName() behaves differently in Internet Explorer, returning an object, compared to Chrome where it returns

While trying to meet my requirements, I encountered a discrepancy between running the page in IE browser versus Chrome. The code worked successfully in IE, but not in Chrome. for(var gridNo=0;gridNo < 30;gridNo++){ var fldId = arry[0]+'_& ...