Responsive Navigation with Custom React Hook

JavaScriptJavaScriptIntermediate
Practice Now

Introduction

In this project, you will learn how to create a custom React Hook called useWindowSize to get the current window size and use it to conditionally render the navigation bar in a web application.

👀 Preview

project preview

🎯 Tasks

In this project, you will learn:

  • Implement the useWindowSize custom Hook to get the current window size
  • Use the useWindowSize Hook in the App component to update the navigation bar based on the window width

🏆 Achievements

After completing this project, you will be able to:

  • Create a custom React Hook to encapsulate reusable functionality
  • Utilize the useState and useEffect hooks to manage state and side effects
  • Conditionally render components based on the current window size

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/DOMManipulationGroup(["`DOM Manipulation`"]) javascript(("`JavaScript`")) -.-> javascript/ToolsandEnvironmentGroup(["`Tools and Environment`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/es6("`ES6 Features`") javascript/DOMManipulationGroup -.-> javascript/event_handle("`Event Handling`") javascript/ToolsandEnvironmentGroup -.-> javascript/bom("`Browser Object Model`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills javascript/variables -.-> lab-300136{{"`Responsive Navigation with Custom React Hook`"}} javascript/data_types -.-> lab-300136{{"`Responsive Navigation with Custom React Hook`"}} javascript/arith_ops -.-> lab-300136{{"`Responsive Navigation with Custom React Hook`"}} javascript/comp_ops -.-> lab-300136{{"`Responsive Navigation with Custom React Hook`"}} javascript/es6 -.-> lab-300136{{"`Responsive Navigation with Custom React Hook`"}} javascript/event_handle -.-> lab-300136{{"`Responsive Navigation with Custom React Hook`"}} javascript/bom -.-> lab-300136{{"`Responsive Navigation with Custom React Hook`"}} react/hooks -.-> lab-300136{{"`Responsive Navigation with Custom React Hook`"}} react/use_state_reducer -.-> lab-300136{{"`Responsive Navigation with Custom React Hook`"}} end

Implement the useWindowSize Hook

To get started, open the editor. You can see the following files from your editor.

├── package-lock.json
├── package.json
├── public
│   ├── index.html
│   └── robots.txt
└── src
    ├── App.css
    ├── App.js
    ├── hooks
    │   └── useWindowSize.js
    ├── index.css
    ├── index.js
    ├── reportWebVitals.js
    └── setupTests.js

In this step, you will learn how to implement the useWindowSize custom Hook to get the current window size.

  1. Open the useWindowSize.js file located in the src/Hooks directory.
  2. In this file, import the necessary dependencies:
import { useEffect, useState } from "react";
  1. Define the useWindowSize function:
import { useEffect, useState } from "react";

export const useWindowSize = () => {
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });

  const changeWindowSize = () => {
    setWindowSize({ width: window.innerWidth, height: window.innerHeight });
  };

  useEffect(() => {
    window.addEventListener("resize", changeWindowSize);

    return () => {
      window.removeEventListener("resize", changeWindowSize);
    };
  }, []);

  return windowSize;
};

Explanation:

  • The useWindowSize function returns an object containing the current window width and height.
  • The useState hook is used to create a state variable windowSize and a function setWindowSize to update it.
  • The changeWindowSize function is defined to update the windowSize state when the window is resized.
  • The useEffect hook is used to add an event listener for the resize event and remove it when the component is unmounted.
  • The windowSize object is returned from the useWindowSize function.

Test the Application

  1. Save the useWindowSize.js file.
  2. Download the dependencies using the npm install command in the terminal, wait for the dependencies to finish downloading and then start the project using the npm start command.
  3. Once the project starts successfully, click on the "Web 8080" to preview it in your browser.
  4. The effect is that when the user resizes the window, the bottom content will show the window width, and the top navigation bar will hide two submenus on small screens and show three menus on large screens.
finished

Congratulations! You have successfully implemented the useWindowSize Hook and used it in the App component to update the navigation bar based on the window size.

✨ Check Solution and Practice

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like