Home > Enterprise >  selection of array when screen width changes
selection of array when screen width changes

Time:07-06

So basically there will be two arrays of images(landscape_images[] and portrait_images[]), one for the portrait view and one for landscape view, when the screen width is landscape then the array containing wide resolution will be displayed in the body and when the screen is in portrait view then the long sized images will be displayed. Both the arrays have a list of objects(source path of the image). how to do it using React,Css,Javascript,Html

CodePudding user response:

You can use window.matchMedia, which I use and prefer as it closely resembles CSS


if (window.matchMedia("(orientation: portrait)").matches) {
   // you're in PORTRAIT mode
}

if (window.matchMedia("(orientation: landscape)").matches) {
   // you're in LANDSCAPE mode
}

Or

if(window.innerHeight > window.innerWidth){
    alert("Please use Landscape!");
}

CodePudding user response:

You could try only using css like this:

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

@media (max-width: 500px) {
    body {
        background-image: url("pic.jpeg");
    }
}

CodePudding user response:

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

export default function App() {
  const [toDisplay,setToDiaplay]= useState("portrait")
  const portrait = 700 // change it with what you think is portrait
  useLayoutEffect(()=>{
  
    const setSize = ()=>{
      if(window.innerWidth > portrait)
       setToDiaplay("landscape")
      else 
       setToDiaplay("portrait")
    }

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

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

The jest of it is you keep track of window size in useLayoutEffect set a state variable when window is grater then your desired size as landscape or when within limit set it to protrait

then accordingly display your images

https://zl0wgk.csb.app/

go this sandbox to try out

  • Related