What could be preventing my state from changing to false when I click the close button on the menu?

Despite initializing my state to false, the problem arises when I open and close my menu. The state never actually becomes false, causing the closing animation of the NavBar to not run as expected.

The component:

import CloseButton from "./CloseButton"
import { useEffect, useState } from "react"

export const NavBar = ({ state, setStateFunction }: { state: boolean, setStateFunction: (value: boolean) => void }) => {
    useEffect(() => {
        console.log(state);
    }, [state]);
    return (
        <div className={`w-[370px] bg-black fixed top-0 left-0 z-40 h-screen transform transition-transform duration-1000 ${state === false ? 'animate-translateX0' : 'animate-translateX'}`}>
            <button className="absolute top-5 right-5 font-bold text-2xl" onClick={() => {setStateFunction(false)}}><CloseButton /></button>
            <div className="ml-6 mt-20">
                <nav className="">
                    <ul className="">
                        <li className="mb-5 hover:translate-x-3 tracking-wider"><a className="hover:text-gray-200 hover:translate-x-3 transition transform" href="">HOME</a></li>
                        <li className="mb-5 tracking-wider"><a href="">CLOTHES</a></li>
                        <li className="mb-5 tracking-wider"><a href="">ELECTRONICS</a></li>
                        <li className="mb-5 tracking-wider"><a href="">FURNITURE</a></li>
                        <li className="mb-5 tracking-wider"><a href="">SHOES</a></li>
                        <li className="mb-5 tracking-wider"><a href="">MISCELLANEOUS</a></li>
                        <li className="mb-5 tracking-wider"><a href="">OFFERS</a></li>
                        <li className="tracking-wider"><a href="">SALE</a></li>
                    </ul>
                </nav>
            </div>
            <span className="ms-madi-regular tracking-wider text-2xl -rotate-12 absolute bottom-24 left-32">WebWish</span>
        </div>
    )
}
export function Header() {
    const [asideBar, setAsideBar] = useState(false)


    return (
        <header
            className="fixed top-0 left-0 right-0 w-screen h-20 p-7 z-20 bg-black overflow-hidden"
        >
            <nav className="flex flex-row justify-between items-center text-customGray pr-4">
                <div>
                    <button onClick={() => 
                                setAsideBar(true)
                       } className="mr-4">
                        {/* <MenuIcon /> */}
                    </button>
                    {asideBar === true && <NavBar state={asideBar} setStateFunction={setAsideBar} />}
                    <button>
                        {/* <SearchIcon /> */}
                    </button>
                </div>
                <span className="ms-madi-regular tracking-wider text-2xl -rotate-12">WebWish</span>
                <div>
                    <button className="mr-3">
                        <a href="/auth/login">
                            {/* <LoginIcon /> */}
                        </a>
                    </button>
                    <button>
                        {/* <ShopIcon /> */}
                    </button>
                </div>
            </nav>
        </header>
    )
}

My index.tsx:

import { Inter } from "next/font/google";
import { NavBar } from "./components/NavBar";
import { useState } from "react";

const inter = Inter({ subsets: ["latin"] });

export default function Home() {
  const [asideBar, setAsideBar] = useState(false);

  return (
    <main
      className={`flex min-h-screen flex-col items-center justify-between p-24 ${inter.className}`}
    >
      <button onClick={() => setAsideBar(true)} className="mr-4">
        Open the sidebar
      </button>

      <button onClick={() => setAsideBar(false)} className="mr-4">
        close sidebar
      </button>

      {asideBar && <NavBar state={asideBar} setStateFunction={setAsideBar} />}
    </main>
  );
}

I have attempted to change the state in various ways, including using toggle. However, the state does not update as expected. It's unclear whether the condition in the component is incorrect or if there is another issue at play.

Answer №1

No details have been provided regarding the application of CSS transitions animate-translateX0 or animate-translateX.

One approach could be to utilize a CSS transition, transitioning between classes like -translate-x-full and translate-x-0 to slide the sidebar in and out smoothly. In order for CSS transitions to function correctly, the element must exist in the DOM before the transition occurs. To simplify this process, consider having the elements always present in the DOM and toggling the -translate-x-full class only.

const CloseButton = () => "CloseButton";
const { useEffect, useState } = React;

const NavBar = ({ state, setStateFunction }) => {
  useEffect(() => {
    console.log(state);
  }, [state]);

  return (
    <div className={`w-[370px] bg-black fixed top-0 left-0 z-40 h-screen transition-transform duration-1000 ${state === false ? "-translate-x-full" : ""}`}>
      <button
        className="absolute top-5 right-5 font-bold text-2xl"
        onClick={() => {
          setStateFunction(false);
        }}
      >
        <CloseButton />
      </button>
      <div className="ml-6 mt-20">
        <nav className="">
          <ul className="">
            <li className="mb-5 hover:translate-x-3 tracking-wider">
              <a className="hover:text-gray-200 hover:translate-x-3 transition transform" href="">
                HOME
              </a>
            </li>
            <li className="mb-5 tracking-wider">
              <a href="">CLOTHES</a>
            </li>
            <li className="mb-5 tracking-wider">
              <a href="">ELECTRONICS</a>
            </li>
            <li className="mb-5 tracking-wider">
              <a href="">FURNITURE</a>
            </li>
            <li className="mb-5 tracking-wider">
              <a href="">SHOES</a>
            </li>
            <li className="mb-5 tracking-wider">
              <a href="">MISCELLANEOUS</a>
            </li>
            <li className="mb-5 tracking-wider">
              <a href="">OFFERS</a>
            </li>
            <li className="tracking-wider">
              <a href="">SALE</a>
            </li>
          </ul>
        </nav>
      </div>
      <span className="ms-madi-regular tracking-wider text-2xl -rotate-12 absolute bottom-24 left-32">WebWish</span>
    </div>
  );
};

const inter = { className: "" };

function Home() {
  const [asideBar, setAsideBar] = useState(false);

  return (
    <main className={`flex min-h-screen flex-col items-center justify-between p-24 ${inter.className}`}>
      <button onClick={() => setAsideBar(true)} className="mr-4">
        Open the sidebar
      </button>

      <button onClick={() => setAsideBar(false)} className="mr-4">
        close sidebar
      </button>

      <NavBar state={asideBar} setStateFunction={setAsideBar} />
    </main>
  );
}

ReactDOM.createRoot(document.getElementById("app")).render(<Home />);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js" integrity="sha512-8Q6Y9XnTbOE+JNvjBQwJ2H8S+UV4uA6hiRykhdtIyDYZ2TprdNmWOUaKdGzOhyr4dCyk287OejbPvwl7lrfqrQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js" integrity="sha512-MOCpqoRoisCTwJ8vQQiciZv0qcpROCidek3GTFS6KTk2+y7munJIlKCVkFCYY+p3ErYFXCjmFjnfTTRSC1OHWQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.tailwindcss.com/3.4.3"></script>

<div id="app"></div>

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

modify CSS style once the modal has been hidden

Is there a way to change the default background color of my table row back to normal after closing the modal window that appears when I click on it? <tr class='revisions'> <td>{{ $revision->date_of_revision->format(' ...

Troubles with Borders and Padding in HTML Elements

Hello everyone, I'm currently facing an issue trying to neatly fit a textbox, select menu, and button all within the same sized div. Each element seems to have strange borders/margins causing them not to display properly (the button ends up below the ...

How can a custom error page be called in Next.js when using an Express server?

I am working on a Next.js app where I have an express middleware that can pass an error to the express instance. Here is the code snippet for better understanding: function (req, res, expressNext) { //Returns an error: expressNext(err) } I am faci ...

Mongoose: An unexpected error has occurred

Recently, I developed an express app with a nested app called users using Typescript. The structure of my app.js file is as follows: ///<reference path='d.ts/DefinitelyTyped/node/node.d.ts' /> ///<reference path='d.ts/DefinitelyTyp ...

Display or conceal a YouTube video with a click

Q1) Is it possible to use JQuery on page load to detect the file name of an image and then dynamically position it on the page with CSS? Q2) What is the most efficient way to achieve this without embedding iframe code inside a specific div.icon element? ...

Next.js Error: The text displayed on the page differs from the HTML rendered by the server

Currently, I am facing an issue with the error "Error: Text content does not match server-rendered HTML." Here is my scenario - I have received a dateTime from an API, for example '2022-12-25T11:22:37.000Z', and I want to display it on a compone ...

Troubleshooting a child process created by electron in Visual Studio Code

I am currently in the process of developing an electron application using typescript and webpack. I have encountered a specific debugging issue with vscode that I would like some assistance with: Context: The main process initiates a child process by call ...

Issue: NullInjectorError: R3InjectorError(AuthorModule)[ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelper]:

While I am going through a tutorial on the abp framework, I encountered an error with the Author route that says "ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AuthorModule)[ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelp ...

Can I switch between different accounts on Auth0?

While utilizing next-auth for user sign-ins, I've noticed that there isn't a clearly visible option to switch accounts after signing in. Additionally, if users enter incorrect credentials, there doesn't seem to be a way to sign in with a dif ...

Exploring ways to integrate Javascript and CSS into a Bootstrap lightbox modal dialog?

Can someone help me figure out how to use the bootstrap lightbox to display a form with specific CSS style and JavaScript code for the form? I'm having some trouble implementing it. I specifically need this setup because I am using Selectize.JS to cr ...

Jquery animation in Wordpress without any need for scrolling

My Wordpress site features some animations that work flawlessly when the site is scrolled. The code looks like this: jQuery(document).ready(function($){ $(window).scroll( function(){ if(!isMobile) { $('.animate_1').each ...

Four-pointed star design with rounded edges

My goal is to create a pixel-perfect star using CSS. I have attempted to achieve this so far, but the star currently has 5 points and I would like it to only have 4 points. Additionally, I am looking for a way to make the corners of the star more rounded. ...

What is the method for aligning inline-block text to the right after a line break?

I am currently encountering a challenge in developing a directory tree using <ul> element, particularly when the text of an item exceeds the width of the container. As I am utilizing the antd React library for this project, my options are somewhat l ...

What is the reason for SVG not being requested during app initialization?

My live site is located at . One issue I am facing is that when a checkbox is clicked, it should quickly turn green with a tick SVG displayed on it. However, upon the initial load of the app, there seems to be a noticeable delay between the background turn ...

What steps can I take to ensure TypeScript compiler approves of variance in calling generic handlers, such as those used in expressJS middleware?

disclaimer: I am a bit uncertain about variance in general... Here is the scenario I am facing: // index.ts import express from 'express'; import {Request, Response} from 'express'; const app = express(); app.use(handler); interface ...

What is causing the content to overflow outside of the navbar on smaller screens or mobile devices?

/* *{ font-family: sans-serif; box-sizing: border-box; margin: 0; padding: 0; overflow-x: hidden; } */ .main { min-height: calc(100vh - 10rem); display: grid; place-items: center; } p { font-size: 4rem; line-height: 1.6; } nav ...

Creating and Injecting Singleton in Angular 2

I have a custom alert directive set up in my Angular app: import { Component } from 'angular2/core'; import { CORE_DIRECTIVES } from 'angular2/common'; import { Alert } from 'ng2-bootstrap/ng2-bootstrap'; @Component({ sele ...

Is it possible to utilize a TypeScript type in conjunction with io-ts?

Currently, I am in the process of validating API responses with io-ts. In my TypeScript setup, I have already defined the following data structure: export type Group = { id: number; name: string; } Now, my objective is to incorporate this type into ...

Mobile Menu in wordpress stays visible after being clicked

I recently created a one-page layout that includes some links. However, when I view the site on my smartphone and open the main menu using the button to click on a link (which scrolls within the same page), I noticed that the mobile menu remains visible a ...

What is the best way to modify onClick events for elements in Ionic v4 with React?

Is there a way for me to interact with a button or IonItemSliding in order to alter the text or color of an element? <IonItemOptions side="start"> <IonItemOption color="success">Yes</I ...