Responsive layout with React Hooks

Tram Ho

Introduce

Responsive is an almost mandatory requirement for websites at the moment when mobile traffic accounts for about 55%, according to statistics here.

So today I will share about how to handle responsive interface with React Hooks, which you will probably need in websites using ReactJS. This article is suitable for those of you who already know ReactJS and Responsive.

Device identification

One of the most commonly used ways when making responsive layouts is to use @media of CSS, the syntax looks like this:

The above code means:

  • With the desktop interface will hide blocks with class isMobile.
  • When the screen size is less than or equal to 1024px, will be processed to display the interface for mobile, ie display on blocks whose class is isMobile and hide blocks whose class is isDesktop.

So in HTML we have to write both blocks with class isMobile and isDesktop, That seems a bit redundant, right?

Navigation userAgent

Another way that can be used is to check the browser’s userAgent, thereby discovering what device is being used, you can refer to the code to determine isMobile on the following website. detect isMobile

Specifically with JavaScript, you can use the isMobile function to check as follows

Then you can use it to test to render the correct HTML you want, as follows:

Check screen size with custom hook

This is the solution I introduce in this article, I still want to use according to the screen size, without wanting the HTML to be redundant.

Then we need to use JS to check the size of the browser, then render based on the test results to display.

Here I have created a custom hook called useViewport, which will return the value width browser, this value will be updated when the browser resizes.

How to use this hook is quite simple, you will compare the value width return with the value you want, in this example I will compare with 1024px as in using responsive with CSS.

Above I have checked if when the browser has the size <=1024px then it will render the HTML for the mobile interface, otherwise render the desktop interface.

Conclude

I created a demo on codepen, you can check the results here. Thank you for reading my article.

Reference source here

Share the news now