Before we start, visit this demo application, this will give you a rough idea of what we are going to discuss in this article.
This article will help you to understand how we can handle responsive UI easily in ReactJS. You must have known about the media queries which was introduced in CSS3.
Media queries are useful when you want to modify your site or app depending on a device’s general type (such as print vs. screen) or specific characteristics and parameters (such as screen resolution or browser viewport width).
Media queries is the first thing that comes in our(the UI developers) mind when we want to develop a responsive website. But sometimes it makes hard for us to handle all the viewport attributes in every CSS file. What if we can manage it at a single place. In case of React app, we can take the advantage of React’s techniques like hooks and HOC.
There a node package called react-responsive which makes it easy to manage media queries.
to install this package use below command,
npm i react-responsive
once installed, you can use it as
A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.
Lets take an advantage of HOC. We will create a HOC which will act as a wrapper to manage the responsive config at a single place. Below is simple code for HOC,
Use this HOC in your component say Home as,
Here is the glimpse of a demo app created using react-responsive.
I hope this article has helped to understand how we can easily create and manage responsive UI in react app using react-responsive and HOC. You can find the final code in the GitHub repo,