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

CSS division nested within the center float division

In my attempt to design a 3-column home layout, I have successfully styled the center, left, and right sections. However, I am facing difficulty in placing two sliders within the middle class. My goal is to have slider1 positioned on top inside the middle ...

The latest grid system in Bootstrap 5 is designed to streamline

I'm attempting to use Bootstrap 5 to create a grid system similar to the image shown below View Image I've been struggling to replicate the grid section shown in the attached image using Bootstrap 5. <div class="container-fluid"> ...

Guide on displaying a tooltip for an object in an Angular component using Bootstrap syntax

i have a data object structured like this var obj = {"test price type ty dynamic ": 10, test: 7, pricetype1u: 0, Price type 3: 0, Price type 2: 0} in my Angular component HTML, with Bootstrap styles applied, I've written the following code ...

Achieve a centered content with a stretched background using Bootstrap 5

Having some trouble with aligning items in a div using align-items-stretch to stretch the background and align-items-center to vertically center the content. It seems that the alignment issue occurs when there's a very long title present. https://i.s ...

Combining jQuery form validation with a PHP script on a single webpage

After implementing jQuery form validation and redirecting using the function btn_onclick() { window.location.href = "http://localhost/loginprivate.php";} from index.php to loginprivate.php, my web app's PHP script is not being executed. The user is re ...

Arranging an array based on relationships between children and parents

I have an array of objects like this: const data = [{id: 3, name: ''}, {id: 4, name: ''}, {id: 5, name: '', parent: 3}, {id: 6, name: '', parent: 5}, {id: 7, name: '', parent: 4}, {id: 8, name: '&ap ...

Error message: Can't find Highcharts in (React JS) environment

I have been encountering an error ReferenceError: Highcharts is not defined, and I've been struggling with this issue for a few days now. Can you provide assistance? In my project, I have Dashboard and Chart files where I import the Chart components ...

What is the best way to create a cube in Three.js with the 4 corner points of the base and a specified height?

Given a JSON with base coordinates, I am looking to generate a cube in Three.js. The height of the cube will be a constant value, such as 1. { "points": [ { "x": 0, ...

Place your cursor over the following element to take control

There is a paragraph that needs to be clipped when hovered over. An issue arises where the H1 text shifts its position. Only the phrase "HOVER ABOVE PARAGRAPH" should be concealed. * { margin: 0; box-sizing: border-box; } .wrapper { displ ...

What are the steps to adjust the size of the Facebook "like" button?

Is there a way to modify the size of the Facebook like button? I attempted to adjust the padding of <a class="connect_widget_like_button clearfix like_button_no_like"> using jQuery, but was unsuccessful. Any suggestions on how this can be achieved? ...

Display and conceal multiple div elements using a timer

Currently, I am working on creating a message box that will display active messages one by one from a MySQL table. The challenge is that the number of divs needed can vary depending on the number of active messages in my database. Using an ajax timer and P ...

Storing JSON data retrieved from an API into a class property using the fetch function: a step-by-step guide

I am faced with the challenge of communicating with a localhost API that I have created in my React application class. This API is responsible for returning a list of JSON data, and my goal is to store this data in a property. Having limited knowledge abo ...

Can the name of the Grunt task target be utilized within attributes?

I have implemented the grunt-replace task to make some content changes in the index.html file. However, I am looking for a way to avoid repeating code unnecessarily. The code snippet below is just an example of what I am trying to accomplish: replace: { ...

Experiencing a blank page on localhost:3000 when utilizing npm in conjunction with ReactJS

click here for the image description var express = require ('express'); //create our app var app = express(); app.use(express.static('public')); app.listen(3000,function(){ console.log('Serve ...

Discover an Easy Way to Scroll to the Bottom of Modal Content with Bootstrap 5 on Your Razor Page

Currently, I am developing a web application that utilizes Razor Pages and Bootstrap 5 modals to showcase dynamic content. The challenge I am facing is ensuring that the content inside the modal automatically scrolls to the bottom when the modal opens or w ...

Avoid altering the state directly; utilize setState() to update it instead. Remember to follow react/no-direct-mutation

Here's the code snippet I'm working with: constructor(props) { super(props) this.state = { loginButton: '', benchmarkList: '' } if (props.username == null) { this.state.loginButton = &l ...

Adjust the size of iCheck jQuery radio buttons

I have implemented the iCheck Plugin for radio buttons in Angular Directive, but I am facing an issue with resizing the radio button to a smaller size. Does anyone have any suggestions or solutions for this? ...

How can I extract data from an XML file and include it in a JSON file using GulpJS?

Being relatively inexperienced with Gulp/Node programming, I am facing some difficulties while trying to accomplish a simple task :) Within my XML file, there exists a node like the following: <widget version="1.1"></widget> My goal is to ext ...

What steps are needed to develop a proper HTML structure for this specific box in order to achieve the desired aesthetics?

Currently working on a box that includes various tags and an input field for adding new tags. The goal is to make this box resemble the tag form used on YouTube: https://i.stack.imgur.com/RSj2p.png This particular layout features a box with existing tags ...

Incorporation of a dynamic jQuery animation

I'm a beginner in jquery and I'm attempting to achieve the following: I want each menu to collapse separately when the mouse hovers over it. The issue is that both menus collapse simultaneously! I know it's probably something simple, but I ...