- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ( <> <BrowserView> <h1> This is rendered only in browser </h1> </BrowserView> <MobileView> <h1> This is rendered only on mobile </h1> </MobileView> </> ); }
Explanation
The element inside <BrowserView> will show only on laptop or PC.
Similarly, the element inside <MobileView> will show only on mobile.
IsMobile and IsBrowser can be used with if-else clause.
Output
Browser view
Mobile view
- Related Articles
- SVG morphing in React JS
- Adding Lottie animation in React JS
- SVG drawing in React JS frontend
- SVG zoom-in and zoom-out in React JS
- Drag and Drop a File feature in React JS
- CSS3 Responsive Web Design
- Creating a Particle Animation in React JS
- Creating a Customizable Modal in React JS
- Creating animated loading skeletons in React JS
- Drawing arrows between DOM elements in React JS using react-archer
- Usage of Responsive Web Design
- Creating an Airbnb Rheostat Slider in React JS
- Creating a Rich Text Editor in React JS
- Creating a PDF in React JS using plain CSS and HTML
- Using pointer light for better lighting in React JS with React-Three-Fiber

Advertisements