Create Breakpoint Observer in React from scratch

Abhik
3 min readOct 25, 2020

If you want to show different content or different layout for mobile devices , tablet devices ,laptop and desktop in your React website then please read this article:

Here we create a Breakpoint Observer which observes the media breakpoints we pass in and returns which breakpoint is currently active , it will actually set the breakpoint to the state .

Step 1 : Creating a Breakpoints Object

This breakPoints object will have all the media queries we want to match..

My breakpoints object

Please Note:

  • You can have as many media queries as you want
  • If you have more than two media queries then except the first and last query all other queries must be limited i.e write the queries like this:

tablet:”(min-width:600px) and (max-width:768px)”,

laptop:”(min-width:769px) and (max-width:1023px)”,

Step 2 : Calling breakPointObserver function

In the parent component I’m creating a state breakpoint. I will use useEffect so that every time breakpoint changes breakPointObserver function will be called. We will pass the setbreakpoint (which is a method to set value to state) to the breakPointObserver function. This will help us later in setting the breakpoint to state breakpoint.

We will create the breakPointObserver function in the next step.

Inside function App in App.js

Step 3 : Creating breakPointObserver function

This breakPointObserver function will be called every time we open this website and also whenever we resize the window.

Inside breakPointObserver function we call another function matchMediaQuery which will take breakpoints object and that setbreakpoint function we passed to breakPointObserver in the previous step.

breakPointsObserver()

Step 4 : Creating the matchMediaQuery function

Inside the matchMediaQuery we will match the media queries we have in breakpoints object .

matchMediaQuery()

Here we are :

  • Running a for..of loop of all keys in the object breakpoints , we have 4 keys there : mobile,tablet,laptop,desktop.

Object.keys(object) will return only the keys from a object

  • If condition to check if the value of each key in the loop matches to current window .

window.matchMedia(mediaquery.matches) will return true if it matches the current window else will return false

Step 5 : Conditional rendering for different breakpoints

Conditional rendering

Here I show both conditionally rendering of classnames and conditionally rendering of content.

That’s It ! We are completely done

If you want a video tutorial on this then watch this:

BreakPoint Observer

Final Code:

breakpointsObserver.js
App.js

Hope This Helps 🎉

--

--

Abhik

Interested in frontend developement & UI design