Setting a const value (true or false) based on the size of the window - a step-by-step guide

While studying, I encountered a challenge:

In the code below, I need to dynamically set useState(false) based on the screen size.

If the screen is larger than 947px, for instance, it should automatically be changed to true.

The issue arises because setting it to "false" causes my navlist(item:nth-child(3)) to disappear at normal screen width but work fine on smaller screens. Conversely, if set to "true", the navlist functions properly on normal screens but opens by default on small screens, which is quite bothersome...

If anyone knows of a method to address this, please share.

import Image from "next/image";
import styles from "../styles/Navbar.module.css";
import React, { useState } from 'react';



const Navbar = () => {

    const [openMenu, setOpenMenu] = useState(false);

    
    return (
        <div className={styles.container}>
            <div className={styles.item} onClick={() => setOpenMenu(!openMenu)}>
                <div className={styles.line} style={{ transform: openMenu ? "rotate(-765deg) translate(-8px, 8px)" : "rotate(0) translateX(0)" }}></div>
                <div className={styles.line} style={{ opacity: openMenu ? "0" : "1" }}></div>
                <div className={styles.line} style={{ transform: openMenu ? "rotate(-855deg) translate(5px, 7px)" : "rotate(0) translateX(0)" }}></div>
            </div>
            <div className={styles.item}>
                
                <div className={styles.call}>
                    <Image src="/img/telephone.png" alt="Telephone" width="32px" height="32px" />
                </div>
                <div className={styles.call}>
                    <div className={styles.text}>ORDER NOW!</div>
                    <div className={styles.text}>012 345 6789</div>
                </div>
            </div>
            <div className={styles.item}>
                <ul className={styles.list} style={{ transform: openMenu ? " translateX(0)" : "translateX(-100%)" }}>
                    <li className={styles.listItem} style={{
                        transform: openMenu ? " translateX(0)" : "translateX(-100%)",
                        opacity: openMenu ? "1" : "0"
                    }}><a href="#">Homepage</a></li>
                    <li className={styles.listItem} style={{
                        transform: openMenu ? " translateX(0)" : "translateX(-100%)",
                        opacity: openMenu ? "1" : "0"
                    }}><a href="#">Products</a></li>
                    <li className={styles.listItem} style={{
                        transform: openMenu ? " translateX(0)" : "translateX(-100%)",
                        opacity: openMenu ? "1" : "0"
                    }}><a href="#">Menu</a></li>
                    <li className={styles.listItem}><a href="#">
                        <Image src="/img/logo.png" alt="Logo" width="160px" height="69px" /></a>
                    </li>
                    <li className={styles.listItem} style={{
                        transform: openMenu ? " translateX(0)" : "translateX(-100%)",
                        opacity: openMenu ? "1" : "0"
                    }}><a href="#">Events</a></li>
                    <li className={styles.listItem} style={{
                        transform: openMenu ? " translateX(0)" : "translateX(-100%)",
                        opacity: openMenu ? "1" : "0"
                    }}><a href="#">Blog</a></li>
                    <li className={styles.listItem} style={{
                        transform: openMenu ? " translateX(0)" : "translateX(-100%)",
                        opacity: openMenu ? "1" : "0"
                    }}><a href="#">Contact</a></li>
                </ul>
            </div>
            <div className={styles.item}>
                <div className={styles.cart}>
                    <Image src="/img/cart.png" alt="Logo" width="30px" height="30px" />
                    <div className={styles.counter}>2</div>
                </div>
            </div>
        </div>
    )
}

export default Navbar

Answer №1

Check out this handy hook function designed to detect the screen width and automatically adjust for screen resizes:

function getWindowDimensions(): { windowWidth: number; windowHeight: number } {
    if (typeof window === 'undefined') {
        const windowWidth = 0;
        const windowHeight = 0;
        return { windowWidth, windowHeight };
    }

    const { innerWidth: windowWidth, innerHeight: windowHeight } = window;

    return {
        windowWidth,
        windowHeight,
    };
}

function UseWindowDimensions(): {
    windowWidth: number;
    windowHeight: number;
} {
    const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());

    useEffect(() => {
        function handleResize(): void {
            setWindowDimensions(getWindowDimensions());
        }

        window.addEventListener('resize', handleResize);

        return (): void => window.removeEventListener('resize', handleResize);
    }, []);

    return windowDimensions;
}

Here's how you can use it in your code:

const { windowWidth } = UseWindowDimensions();

You can then create a condition within a useEffect that monitors changes in the 'windowWidth' value to control the state of a boolean variable.

 useEffect(()=> {
    windowWidth > 947 ? setOpenMenu(true) : setOpenMenu(false)
 },[windowWidth])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Click the icon to introduce a fresh row into the table

I have embedded a table with a "plus" font awesome icon. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorig ...

Troubled by the mysterious CORS filter issue in Play

I have an app on Google Play. Here's my application.conf file: include "silhouette.conf"; play.modules.enabled += "modules.SilhouetteModule" play.filters.enabled += "play.filters.cors.CORSFilter" play.filters.hosts { allowed = ["."] } play.filt ...

What are the best techniques for positioning text next to images in HTML and CSS?

I have attempted to position the text in close proximity to the images as shown in the picture below (to allow for spacing in the middle). As depicted in the image, the "AVENUE FOR GROWTH" and "NETWORKING OPPORTUNITIES" texts are near Man's hand and w ...

Utilizing React Router Dom to Showcase Home Route from a Sub-Route

www.mywebsite.com www.mywebsite.com/ www.mywebsite.com/1 I need my website to show the same content for each of the links above. Currently, it is not displaying anything for www.mywebsite.com and www.mywebsite.com/ function App() { return ( <Rout ...

What could be causing the issue with the rendering of data in the react table?

My aim was to display data using React Table on react js and I followed the guidance from a specific website. Below is my code snippet: import React, { Component } from 'react'; import './App.css'; import ReactTable from "react-table ...

Using CSS to create various h1 headings with distinct colors and sizes

I am currently working with CSS and HTML, trying to replicate the design shown in this image: https://i.stack.imgur.com/Uyczp.png Initially, I attempted to achieve this by using multiple h1 tags, but after researching further, I realized that it is gener ...

An HTML attribute that functions like autofocus in the select tag

Is there a way to set the default focus on a select tag in HTML, similar to how autoFocus works for textboxes? I am looking to make a select tag automatically focused when the page loads. Is there a method to achieve this? ...

Discovering the import path of Node modules in ReactAlgorithm for determining the import path of

Software Development In my current project, I am utilizing Typescript along with React. To enhance the application, I integrated react-bootstrap-date-picker by executing yarn install react-bootstrap-date-picker. Unfortunately, there is no clear instruct ...

Resizable icon next to inline element caused width adjustment

I have a group of individuals listed, each with two elements side by side: a "contact me" button (an 'a' element with a fontawesome icon) and a tag displaying the user type (span element). Some users do not have a tag, and when there is one prese ...

`The Conundrum of Basic HTML Parsing`

Hello, I am currently working on extracting professor names and comments from the ratemyprofessor website by converting each div into plaintext. The following is the structure of the div classes that I am dealing with: <div id="ratingTable"> <div ...

How to effectively utilize Python to compare HTML files

Can the HTML be compared differently as shown below? html_1 = "<h1>text<h1>" html_2 = "<h2>text<h2>" Using Google's diff_prettyHtml may not yield accurate results. If I want to say that 1 has changed to 2: <h <del styl ...

The statusText variable for getXMLHTTP object is not found when the status is not equal to

Earlier, I posted about this issue before isolating the problem. Now that I have isolated it, I wanted to repost with a clearer focus on the two functions causing the problem. Whenever I update my State, it triggers the getCity function. The call is being ...

Submenu Positioning Problem Identified in Firefox Display

I am currently working on a menu design for a website and encountered an unusual issue while testing it in Firefox. In the provided fiddle link, you can view the menu layout where hovering over the information button should display a submenu directly below ...

choose a distinct value for every record in the table

My goal is to only change the admin status for the selected row, as shown in the images and code snippets below. When selecting 'in-progress' for the first row, I want it to update only that row's status without affecting the others. <td ...

The functionality of cloning in jQuery may encounter an issue where the text field remains enabled if the user selects an option labeled "other

Currently, I am working on a jQuery clone with my existing code and everything is functioning well. In the first scenario, if the user selects other from the dropdown menu, the text field becomes enabled. In the second scenario, when the user clicks ...

Establishing routes for next-connect's page navigation

After setting up a server using next-connect, the next step is to direct requests to the pages folder within the nextjs program. Below is an example of a server js file implementing this: const nc = require("next-connect"); const {auth} = requ ...

The state in Reactjs is not displaying as expected

Check out my ReactJS todo app that I created. However, I am facing an issue with deleting todos. Currently, it always deletes the last todo item instead of the one I click on. For example, when trying to remove 'Buy socks', it actually deletes ...

What is causing my server to mysteriously alter the style of index.html?

After setting up a node, express, react app, I realized that when express serves static content like my CSS file, the source of the index.html shows an additional style tag in the head section: <style type="text/css">* {}</style> I confirme ...

Incorporate JavaScript to dynamically fetch image filenames from a directory and store them in an array

By clicking a button, retrieve the names of images from a folder and store them in an array using jQuery. I currently have a script that adds images to the body. In the directory images2, there are 20 images stored. The folder images2 is located in my i ...

Float and tap

Can someone assist me with my code? I have 4 identical divs like this one, and when I hover over a link, all the elements receive the same code. <div class="Person-team"> <div class="profile-pic-d"> <a cl ...