Before Tailwind CSS or Bootstrap came into being, there existed an old arcane magic that all CSS and frontend developers consulted and used when they wanted to create truly responsive applications: Media Queries.
Ranging from mobile devices to tablets and desktops and beyond, frontend developers knew that mastery of media queries was the key to making their works of art accessible to any and every user.
In this blog post, you’ll learn how to use this amazing tool, now defined as the react-responsive package found on npm. Jump in, young magician, it’s time for you to build the pyramid of knowledge.
react-responsive is an npm package that allows you to create truly responsive designs in your React projects. It uses the combined power of media queries and breakpoints to define DOM elements the developer wants to show and hide. It’s another powerful tool in your arsenal as a React developer.
If you love mobile-first designs, responsive designs, or if you want your app to scale up and down depending on screen size while retaining its structural integrity, then react-responsive is the package for you.
First, begin by creating a new React project with no dependencies. We’ll perform an npm install of the react-responsive package with npm i -S react-responsive
.
Just so you know, react-responsive anticipates different use cases, so we can use it with Hooks or with components. Next up, go to your app.js
and import the package with import { useMediaQuery } from 'react-responsive'.
In the app.js
function, we’re going to define media queries like these:
const isMobileDevice = useMediaQuery({ query: "(min-device-width: 480px)", }); const isTabletDevice = useMediaQuery({ query: "(min-device-width: 768px)", }); const isLaptop = useMediaQuery({ query: "(min-device-width: 1024px)", }); const isDesktop = useMediaQuery({ query: "(min-device-width: 1200px)", }); const isBigScreen = useMediaQuery({ query: "(min-device-width: 1201px )", });
Here, we’re using the media queries to serve up content if the device is a particular size. Speaking of, react-responsive is so awesome that we can force content to adhere to a size with the device
prop.
This has keys like orientation
, scan
, aspectRatio
, deviceAspectRatio
, height
, etc., and they allow you to simulate a device for testing in environments that would not ordinarily allow for it.
Now, back to our code.
Create a folder in your src
and name it components
. In there, create five new folders: big-screen
, desktop
, laptop
, mobile
, and tablet-mobile
.
Each of these folders will have a component.jsx
file and a styles.css
file. We’ll now have long blocks of code because we want to build the pyramid, so brace yourself, young magician. Are you ready? Alright, let’s dive in.
// big-screen.component.jsx import React from 'react' import './big-screen.styles.css' export const BigScreen = () => { return ( <div className="big-screen"> <p>Whoops! I'm in big screen mode.</p> <p>This is the base of the pyramid</p> </div> ) }
// big-screen.styles.css .big-screen { width: 600px; height: 100px; background: #7c52bf; margin: 0 auto; } .big-screen p { padding-top: 2%; }
// desktop.component.jsx import React from 'react' import './desktop.styles.css' export const Desktop = () => { return ( <div className="desktop"> <p>Whoops! I'm in desktop mode.</p> <p>But if you see anything below me, i am now in Laptop mode</p> </div> ) }
// desktop.styles.css .desktop { width: 400px; height: 100px; background: #b097d8; margin: 0 auto; } .desktop p { padding-top: 2%; }
// laptop.component.jsx import React from 'react' import './laptop.styles.css' export const Laptop = () => { return ( <div className="laptop"> <p>Whoops! I'm in laptop mode.</p> <p>But if you see anything below me, i am now in Big Screen mode</p> </div> ) }
// laptop.styles.css .laptop { width: 500px; height: 100px; background: #9674cb; margin: 0 auto; } .laptop p { padding-top: 2%; }
// tablet-mobile.component.jsx import React from "react"; import "./tablet-mobile.styles.css"; export const TabletMobile = () => { return ( <div className="tablet-mobile"> <p>Whoops! I'm in tablet-mobile mode.</p> <p>But if you see anything below me, i am now in Desktop mode</p> </div> ); };
// tablet-mobile.styles.css .tablet-mobile { width: 300px; height: 100px; background: #cab9e5; margin: 0 auto; } .tablet-mobile p { padding-top: 2%; }
// mobile.component.jsx import React from 'react' import './mobile.styles.css' export const Mobile = () => { return ( <div className="mobile"> {/* <p>Whoops! I'm in mobile mode.</p> */} </div> ) }
// mobile.styles.css .mobile { width: 80px; height: 80px; margin: 0% auto; border-radius: 50%;8 box-shadow: 15px 15px 0 0 #e4dcf2; }
Whew! That was a lot of code! But don’t fret, young magician, it is easily understood. All we did in the above files was create a different component for a different screen size, so that when you enter into a new screen resolution, a new level to our pyramid appears.
If you need to see how this works, you can check out my GitHub repo and live version of the app.
Now, let’s go back to app.js
. In the return statement, place this in:
<h1>React Responsive - a guide</h1> {isMobileDevice && <Mobile />} {isTabletDevice && <> <TabletMobile /> {isDesktop && <Desktop />} {isLaptop && <Laptop />} {isBigScreen && <BigScreen />} </>}
Here, we’re using React’s truthy statements to define the viewport size and the content. Aside from handling the breakpoints from methods as defined in the app.js
, we can also do this through components.
In this case, you’ll import the component MediaQuery with import MediaQuery from react-responsove
and using it in components like this:
<MediaQuery minDeviceWidth={1224}> <p>Manipulate me with the powers of React Responsive</p> </MediaQuery>
Congratulations for making it to the end of this lesson! Now all we have to do is test the app we just built together.
To do so, open your browser’s dev tools window and set the viewport
to responsive
. Then, create the pyramid shape by adjusting it from the smallest size to the largest.
I’m glad we made this happen together, young magician. Now with the pyramid of truth unveiled to you, go forth and conquer your world. I can’t wait to see the amazing applications you will build with this new knowledge. Until next time.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowSOLID principles help us keep code flexible. In this article, we’ll examine all of those principles and their implementation using JavaScript.
JavaScript’s Date API has many limitations. Explore alternative libraries like Moment.js, date-fns, and the new Temporal API.
Explore use cases for using npm vs. npx such as long-term dependency management or temporary tasks and running packages on the fly.
Validating and auditing AI-generated code reduces code errors and ensures that code is compliant.
One Reply to "Using react-responsive to implement responsive design"
Good article. However, this doesn’t adhere to the principle of DRY (Do not Repeat Yourself). Creating a separate component for each viewport is far from ideal and doesn’t scale well. Consider using only one component and one stylesheet that contains each viewport’s styles nested under the corresponding media query. The mobile styles should be applied first and progressively overwritten by the styles for larger viewports because those devices are typically more powerful. If it’s very important for you not to load unnecessary styles then you can dynamically import the correct stylesheet based on the viewport into one component.