I am importing my breakpoint module CSS into JavaScript and am getting an object like this:
const breakpoints = {
large: "992px",
medium: "768px",
small: "500px",
tiny: "320px",
xlarge: "1384px"
}
From window.innerWidth
I am able to get an integer value of the current browser window width. I would like to use a function that tells the named breakpoint from the window width. For example, a value of 640
would return medium
.
The logic is hurting my brain. How can I do it?
You need to sort your set of values by the integer values and then filter those for values too small and take the first that is big enough.
Object.keys(breakpoints)
.sort((a,b) => parseInt(breakpoints[a], 10) - parseInt(breakpoints[b], 10))
.filter((s) => { return parseInt(breakpoints[s], 10) > 640 })[0]