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

Executing a component's method using HTML in Vue2

In my development project, there is a .vue file named ServiceList. This file imports the component called Information.vue. My objective is to execute the code from the Information component in a loop within the template of the ServiceList file. Here is an ...

Failing to reach the nested if statements within a switch case block

Before removing my question, please read this. Despite testing with console.logs, my code does not enter the if statements. I have not come across a similar solution to my issue. In an attempt to address any timing or asynchronous problems, I added a use ...

Unlocking a targeted list in AngularJS

I have the following code snippet that I am using to implement ng-repeat in an Angular project. My goal is to display only the list item that I click on, but currently, when I click on the symbol ~, it displays all the lists. Is there a way to specify cer ...

"Access denied: Resteasy and ajax do not support this method (error

Encountering a login problem, although registration is functioning smoothly. Tech stack - HTML/AJAX/JQuery->Resteasy (Wildfly 10.1.0 Final) The URL - https://www.test.com/login.html - (actual URL name altered) Upon submitting the form with method type ...

Issue with Next.js middleware: Unable to locate module 'fs'

Encountering the following error in my Next.js _middleware file while attempting to initialize Firebase admin V9. Is there a solution available for this issue? ./node_modules/@google-cloud/storage/build/src/bucket.js:22:0 Module not found: Can't resol ...

Is there a way to modify a specific item within a useState Array in Reactjs?

Having a useState hook that stores data in the following structure: const [orderData, setOrderData] = useState({ demoData1: '', demoData2: '', demoData3: '', demoArrayData: [{itemName: '', itemNumber: ...

The outcome of the Python web crawling did not meet our expectations

After using Selenium to scrape web data, I encountered an issue where it only displayed 96 out of 346 products instead of the expected 346. Does anyone have suggestions on how to fix this problem? The crawling code is placed right after the loop for clicki ...

What is the best way to insert a React component or raw HTML into another React component?

Dealing with raw HTML markup returned from an AJAX call can be tricky in React. I've tried using dangerouslySetInnerHTML, but React just throws errors when I do. It's like trying to navigate through a maze. After some trial and error, I decided ...

The Evolution of Alternatives to contentEditable

Related: ContentEditable Alternative I am curious about the timeline of online WYSIWYG editors prior to the existence of contentEditable. I remember using GDocs and GMail with rich-text features that functioned similarly to contentEditable. I would appre ...

React JS is throwing an error saying it can't read the property of handleClick because it is undefined

I have been experimenting with adding a new class to a div that already has the class option using React state. It's worth noting that I am new to React. Below is my code. I have declared handleClick() after the constructor class. I have included bin ...

Using jQuery to append content with a variable as the source

Recently delving into jQuery and encountering an issue with getting my variable inside src when using append. Either it's not functional at all, or just displaying the variable name in string form in the console. Here is the code causing trouble: va ...

Retrieve the Data from Input Fields with Matching Classes and Transmit to a Script Using AJAX Request

I am working on a form that includes multiple input fields: <input type="text" class="date" name="date[]" onkeyup="showHint()" /> <input type="text" class="date" name="date[]" onkeyup="showHint()" /> <input type="text" class="date" name="da ...

Conceal the <p> element when the user interacts with the internal href

After creating this document using JQuery, whenever the user clicks on different internal links, a div with id = "change" is loaded which effectively "erases" the content. My challenge at the moment is that while images are successfully deleted, text rema ...

Modifying a div element upon the successful completion of an ajax/json request

Currently, I have a form on my webpage for creating a new album. Alongside this form, there is also a delete album form. After successfully creating an album, I want to automatically update the checkbox list in the delete album form with the details of the ...

Material Design UI Table: Conceal Columns for Compact Screens

I'm facing some issues while attempting to hide columns in a MUI table when viewing on smaller screens. Despite following the guide closely, I am encountering unexpected outcomes. I am interested in learning about any potential solutions or workaround ...

Attempting to Send an Ajax Request and Utilize the Result within a React Component

I am having issues with my tweet box component. I have a submit function that triggers the getAllTweets function when called. The problem is that I am unable to capture the value of the field and pass it on to the getAllTweets function in order to create ...

Encountering difficulty in identifying the error during data fetching on the server side of a Next.js application

I am attempting to troubleshoot an error with my Next.js server-side data fetching, but I am encountering two problems. export async function getStaticProps() { try { const fetchUrl = "some api url"; const resp = await axios.get(fetchUrl); ...

Items in the list will flash as you drag them in Firefox

I compiled a list of components (basic labels) and implemented a drag-and-drop feature on them (inspired by: https://www.w3schools.com/howto/howto_js_draggable.asp). Whenever I move one component with jerky motion, all the components below in the list star ...

Styling elements with CSS to achieve proper positioning

I am in search of a way to align rows utilizing the style property. The following HTML code is being transformed using XSL: <span style="white-space: pre; font-size: 8pt; font-family: Lucida console, Courier ">&lt;40 : item1</span>&l ...

Identify whether the page is being accessed through the Samsung stock browser or as an independent web application

Hey there! I am on a mission to determine whether my webpage is being accessed through Samsung's default browser or as a standalone web app saved on the homescreen. Unfortunately, the javascript codes I have come across only seem to work for Safari an ...