Skip to content
Related Articles
Open in App
Not now

Related Articles

How to update layouts based on viewport dimension using useViewport hook ?

Improve Article
Save Article
  • Last Updated : 18 Feb, 2023
Improve Article
Save Article

In today’s digital landscape, web applications need to be responsive and adaptable to different screen sizes and devices. The useViewport hook in React allows developers to easily access the dimensions of the viewport and respond to changes in the viewport size, making it a powerful tool for building responsive web applications.

useViewport hook is a custom hook that allows you to respond to changes in the viewport size in a React application. It provides you with the current viewport dimensions, such as the width and height of the viewport, and allows you to update your component’s layout or styling based on these dimensions. react-viewport-hooks is a library that provides a set of hooks for working with viewport dimensions and media queries in a React application. The useViewport is one of the hooks provided by this library and allows you to get the current viewport dimensions and respond to changes in the viewport size. For example, we can use the useViewport hook to create a responsive navigation bar that collapses into a hamburger menu on smaller screens. Or, a layout that changes the number of columns in a grid depending on the width of the viewport. This allows for a seamless user experience across different devices and screen sizes, as the layout will adapt to the viewport size in real-time.

Prerequisites:

Syntax:

const {vw,vh} = useViewport(); 

Parameters:

  • vw: vw stands for “viewport width”.
  • vh: vh stands for “viewport height”.

They are units of measurement used in CSS to describe the size of elements relative to the viewport size.

Creating React Application:

Step 1: Make a project directory, head over to the terminal, and create a react app named useviewport-example using the following command:

npx create-react-app useviewport-example

Step 2: After the useviewport-example app is created, switch to the new folder useviewport-example by typing the command below:

cd useviewport-example

Step to include useViewport hook:

To use the useViewport hook in your project, you will need to install the react-viewport-hooks package first. You can install it by running the following command in your terminal:

npm install react-viewport-hooks

Then, you can import the hook in your React component:

import { useViewport } from 'react-viewport-hooks';

Project Structure:

We will modify the folder and keep the files we need for this example. Now, make sure your file structure looks like this:

Project structure

Example 1: Adjusting a grid layout to a list layout when the viewport becomes narrower. We will check if the viewport width is less than 768px. If it is, the layout variable is set to ‘list’. If not, the layout variable is set to ‘grid’. Then, we will render the div. Inside it, a ternary operator is used to check the layout variable, if it’s a grid, the component <GridLayout /> is rendered, otherwise <ListLayout /> is rendered.

App.js: Add the following Javascript code to App.js file

App.css: Add the following code to App.css to style the application.

Javascript




import React  from 'react';
import { useViewport } from 'react-viewport-hooks';
  
import './App.css';
  
  
const GridLayout = () => {
    return (
        <div className="grid-layout">
            <div className="grid-item">Grid-Item 1</div>
              <div className="grid-item">Grid-Item 2</div>
              <div className="grid-item">Grid-Item 3</div>
              <div className="grid-item">Grid-Item 4</div>
        </div>
    );
};
  
const ListLayout = () => {
    return (
        <ul className="list-layout">
            <li className="list-item">List-Item 1</li>
             <li className="list-item">List-Item 2</li>
              <li className="list-item">List-Item 3</li>
              <li className="list-item">List-Item 4</li>
           </ul>
    );
};
  
const App=()=> {
  
    const { vw } = useViewport();
    console.log(vw);
  
    let layout = 'grid';
     if (vw < 768) {
        layout = 'list';
      }
    return (
        <div>
            { layout === 'grid' ? <GridLayout /> : <ListLayout /> }
        </div>
     );
}
  
export default App;

CSS




.grid-layout {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 10px;
}
  
.grid-item {
    background-color: green;
    padding: 10px;
    text-align: center;
    color: white;
    font-weight: bold;
}
  
.list-layout {
    list-style-type: none;
    padding: 0;
}
  
.list-item {
    background-color: pink;
    padding: 10px;
    margin-bottom: 10px;
    text-align: center;
}

Step to run the application: Run the application by using the following command:

npm start

Output: By default, the React project will run on port 3000. You can access it at localhost:3000 on your browser. Open DevTools by pressing F12 and click on the “Device Toggle Toolbar” to adjust the viewport.

Output: Using the viewport hook to update layouts based on viewport dimensions.

As the viewport size decreases, the layout of the elements changes from a grid layout to a list layout.

Example 2: In this example, the useViewport hook returns the current width of the viewport. If the width is greater than 768, then a full navigation bar is displayed. If the width is less than or equal to 768, then a “Menu” button is displayed instead. When the “Menu” button is clicked, the state of menuOpen is updated using setMenuOpen, and the submenu is displayed if menuOpen is true.

App.js: Add the following Javascript code to App.js file

App.css: Add the following code to App.css to style the application.

Javascript




import React, { useState } from 'react';
import { useViewport } from 'react-viewport-hooks';
import './App.css'
  
const Navbar = () => {
    const { vw } = useViewport();
    const [menuOpen, setMenuOpen] = useState(false);
  
      return (
        <nav>
            <ul>
                <li>Home</li>
                {vw > 768 ? (
                      <>
                           <li>About</li>
                        <li>Contact</li>
                    </>
                ) : (
                <li onClick={() => setMenuOpen(!menuOpen)}>
                    Menu
                    {menuOpen && (
                    <ul>
                               <li>About</li>
                               <li>Contact</li>
                    </ul>
                        )}
                 </li>
                )}
            </ul>
        </nav>
      );
};
  
export default Navbar;

CSS




nav {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem;
}
  
ul {
    list-style: none;
    display: flex;
    margin: 0;
    padding: 0;
}
  
li {
    margin: 0 1rem;
}
  
ul ul {
    display: none;
    position: absolute;
    background-color: lightgray;
}
  
li:hover>ul {
    display: block;
}

Step to run the application: Run the application by using the following command:

npm start

Output: By default, the React project will run on port 3000. You can access it at localhost:3000 on your browser. Open DevTools by pressing F12 and click on the “Device Toggle Toolbar” to adjust the viewport.

Output: Creating a responsive navigation bar using the useViewport hook.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!