Open In App

Create a Custom Hook to Make Next.js Apps Responsive

Last Updated : 07 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, We’ll be creating a custom hook that will be useful for conditionally rendering components in a responsive layout. We’re going to check the screen size and accordingly render the components in a Next.js app.

First Let’s start by creating a Next.js project.

Create Next.js project: Run the following command in the terminal

npx create-next-app gfg-next

Project Structure: It will look like this.

 

Step 1: Create a custom file /utils/useIsMobile.js and add the following code to it.

Javascript




import { useEffect, useState } from "react";
  
const useIsMobile = () => {
    const [width, setWidth] = useState(0);
    const handleWindowSizeChange = () => {
        setWidth(window.innerWidth);
    };
  
    useEffect(() => {
        handleWindowSizeChange();
  
        /* Inside of a "useEffect" hook add 
           an event listener that updates
           the "width" state variable when 
           the window size changes */
        window.addEventListener("resize"
            handleWindowSizeChange);
  
        // Return a function from the effect 
        // that removes the event listener
        return () => {
            window.removeEventListener(
                "resize", handleWindowSizeChange);
        };
    }, []);
  
    return width <= 700;
};
  
export default useIsMobile;


Step 2: Update the index.js file with the below code

Javascript




import Head from "next/head";
import styles from "../styles/Home.module.css";
import useIsMobile from "../utils/useIsMobile";
  
export default function Home() {
    const isMobile = useIsMobile();
  
    return (
        <div className={styles.container}>
            <Head>
                <title>Create Next App</title>
                <link rel="icon" href="/favicon.ico" />
            </Head>
            {isMobile ? <Mobile /> : <Desktop />}
        </div>
    );
}
  
function Mobile() {
    return (
        <div className={styles.main}>
            <h1 className={styles.title}>
                Welcome to 
                    <a href="https://nextjs.org">
                    Next.js!
                </a>
            </h1>
            <h1 className={styles.subtitle}>
                Mobile UI
            </h1>
            <p className={styles.description}>
                Get started by editing mobile 
                component in
                <code className={styles.code}>
                    pages/index.js
                </code>
            </p>
        </div>
    );
}
  
function Desktop() {
    return (
        <div className={styles.main}>
            <h1 className={styles.title}>
                Welcome to 
                <a href="https://nextjs.org">
                    Next.js
                </a>
            </h1>
            <h1 className={styles.subtitle}>
                Desktop UI
            </h1>
            <p className={styles.description}>
                Get started by editing desktop 
                component in
                <code className={styles.code}>
                    pages/index.js
                </code>
            </p>
        </div>
    );
}


We have created separate components for both mobile and desktop code in a file and our main component ‘Home’ just renders the particular component according to the user’s current screen size.

Step 3: Create a Home.module.css file in the styles folder and add the below CSS code

CSS




.container {
    padding: 0 2rem;
}
  
.main {
    min-height: 100vh;
    padding: 4rem 0;
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
  
.title a {
    color: #0070f3;
    text-decoration: none;
}
  
.title a:hover,
.title a:focus,
.title a:active {
    text-decoration: underline;
}
  
.title {
    margin: 0;
    line-height: 1.15;
    font-size: 4rem;
}
  
.subtitle {
    line-height: 1.15;
    text-decoration: underline;
}
  
.title,
.description {
    text-align: center;
}
  
.description {
    margin: 4rem 0;
    line-height: 1.5;
    font-size: 1.5rem;
}
  
.code {
    background: #fafafa;
    border-radius: 5px;
    padding: 0.75rem;
    font-size: 1.1rem;
    font-family: Menlo, Monaco, Lucida Console, 
        Liberation Mono, DejaVu Sans Mono,
        Bitstream Vera Sans Mono, 
        Courier New, monospace;
}


Steps to run the application: To run the app, type the following command in the terminal.

npm run dev

Output: Now open your browser and go to http://localhost:3000/, you will see the following output.

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads