Skip to content
Advertisement

Another way of implementing an If else statement for viewport check?

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" }
    }
  }

Advertisement

Answer

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" }
    }
  }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement