Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Another way of implementing an If else statement for viewport check? Anyone see a way around it?

I am dealing with a simple premise that questions viewport and based on that i am returning different aspectRatios.
Now, for some reason i always have else return as true and then millisecond later the viewport gets validated. The result is that i am picking 2 aspect ratios and that makes me download additional image, which presents as unnecessary.
I am wondering if there is a way around it, or to write it differently?

const getResponsiveAspectRatio = (): {
    s: ValidRatios
    m: ValidRatios
    l: ValidRatios
  } => {
    if (viewport?.isWrapperWidthAndUp) {
      return { s: "4-3", m: "4-3", l: "4-3" }
    } else if (viewport?.isLargeDesktopAndUp) {
      return { s: "1-1", m: "1-1", l: "1-1" }
    } else if (viewport?.isDesktopAndUp) {
      return { s: "3-4", m: "3-4", l: "3-4" }
    } else if (viewport?.isTabletAndUp) {
      return { s: "3-4", m: "3-4", l: "3-4" }
    } else {
      return { s: "1-1", m: "1-1", l: "1-1" }
    }
  }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Check for viewport explicitely first

const getResponsiveAspectRatio = (): {
    s: ValidRatios
    m: ValidRatios
    l: ValidRatios
  } => {

    if (!viewport) {
      // Viewport is not initialized
      return null; // return null or some value that the calling code can 
                   // handle and will not result in downloading resources
    }
    else if (viewport?.isWrapperWidthAndUp) {
      return { s: "4-3", m: "4-3", l: "4-3" }
    } else if (viewport?.isLargeDesktopAndUp) {
      return { s: "1-1", m: "1-1", l: "1-1" }
    } else if (viewport?.isDesktopAndUp) {
      return { s: "3-4", m: "3-4", l: "3-4" }
    } else if (viewport?.isTabletAndUp) {
      return { s: "3-4", m: "3-4", l: "3-4" }
    } else {
      return { s: "1-1", m: "1-1", l: "1-1" }
    }
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading