Device Detection and Responsive Design in React JS

In this article, we will see how to render a page according to device but without using if-else clause. For this, we will use the react-device-detect package. This feature can help us create responsive webpages without using any media queries. So, let's get started.

Example

First create a React project −

npx create-react-app tutorialpurpose

Go to the project directory −

cd tutorialpurpose

Download the react-device-detect package −

npm install react-device-detect --save

We will use this package to add default media queries or default conditional rendering which are premade inside the package.

Add the following lines of code in App.js

import {
   BrowserView,
   MobileView,
   isBrowser,
   isMobile,
} from "react-device-detect";

export default function App() {
   return (
      
         
            

This is rendered only in browser

This is rendered only on mobile

> ); }

Explanation

  • The element inside will show only on laptop or PC.

  • Similarly, the element inside will show only on mobile.

  • IsMobile and IsBrowser can be used with if-else clause.

Output

Browser view

Mobile view

Updated on: 2021-09-29T08:42:43+05:30

939 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements