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

Tips for positioning a mat-form-field beside an h1 tag

I've been attempting to place an h1 next to a mat-form-field from Angular Material, but I'm encountering some difficulties. Here's what I've attempted so far: <div class="mat-elevation-z8"> <mat-form-field> <mat-l ...

Why is it necessary to include a dollar sign before interpolation in Angular?

While diving into a tutorial, I stumbled upon a piece of code that piqued my curiosity. I grasped the concept that appending a dollar sign as a suffix indicates observability, but I wonder why the dollar sign was also prefixed to this.log(`updated hero i ...

Struggling with TypeScript and JsObservable? Let us assist you!

Having previous experience with JSRender, JSViews, and JSObservables, I recently embarked on a new project using TypeScript. Unfortunately, I am struggling to understand how to properly utilize TypeScript in my project, especially when it comes to referenc ...

How can I ensure text remains within a parent div and is positioned above an image?

After writing the following HTML and CSS, an issue arose when resizing the page: <div style="position: relative;"> <img width="100%" src="images/some.jpg"> <div class="header"> <h1>my header</h1> ...

The useContext function is not giving the expected value, even though all the conditions appear to be

After reading through several discussions about the "useContext returns undefined" issue, I still haven't found a solution to my problem. I'm currently working on a weather application using nextJS, the geolocation browser API, and the openweathe ...

Tips for embedding HTML/CSS snippets in backticks when using TypeScript with AngularJS

Does anyone else experience the issue of their Angular 2 templates showing up as gray text in Visual Studio Code? I'm unable to use autocomplete or see my CSS properly. Is this a settings problem or is there a plugin that can solve this? BTW, I am us ...

Integrate a scrollbar seamlessly while maintaining the website's responsiveness

I encountered an issue where I couldn't add a scrollbar while maintaining a responsive page layout. In order to include a scrollbar in my datatables, I found the code snippet: "scrollY": "200px" However, this code sets the table size to 200 pixels r ...

Writing a CSV file to AWS S3 proves to be unsuccessful

I have been working with TypeScript code that successfully writes a CSV file to AWS S3 when running locally. However, I have recently encountered an error message: s3 upload error unsupported body payload object NOTES: The code is not passing creden ...

What is the best way to place a horizontal line behind buttons in a design?

Hello, I was experimenting with creating a background line behind the buttons on my webpage. Previously, I used an image for this purpose but now I want to achieve the same effect using a line. <div class="feedback-option"> <div class="radios2" ...

Tips for inserting a dash between dynamic route names in a Next.js URL

I'm working on a dynamic route called pages/post/[postname].tsx. However, when I provide a name to the dynamic route, the URL displays the name encoded with characters like %20 and %E2. What I'd like is for the name to show in the URL with dashes ...

Is it possible to serve CSS using relative paths that go beyond the URL root?

I've encountered a file path issue with my HTML and CSS files. My HTML file is located in: src/test/html/index.html And the corresponding CSS file is in: src/test/css/index.css In the HTML file, the CSS is linked using: <link rel="stylesheet" ...

Scroll bars on JQuery UI dialog

When using the jquery UI Dialog modal, everything appears correctly in Firefox and Chrome. However, in IE8, scroll bars suddenly appear. Is there a way to remove them? ...

Having trouble retrieving mobiscroll instance in Angular with Ionic

I'm facing an issue with accessing the instance of my mobiscroll widget in Angular 4 with Ionic Framework. Despite following all the correct steps, the actual widget won't get selected. Below is the code for the widget: <mbsc-widget [options ...

Creating multiple-to-multiple relationships in Express: A beginner's guide

In developing a small API with Express and TypeScript, I am faced with handling both POST and GET requests. The POST request involves receiving a list of organizations, which may have daughter organizations that can also have their own daughters, creating ...

Employ CSS to target the initial and final items within sets of identical elements

I created the following CSS styles: div { width: 300px; text-align: center; } p:not(.vrt) { text-align: left; } p.vrt { writing-mode: vertical-rl; display: inline-block; } div :nth-child(1 of p.vrt) { margin-left: 0; } div :nth-last-child(1 of ...

Need assistance with CSS layout: How to extend a div to the bottom of the page

I am currently working on a design layout that includes a 'header' section with a logo and links, as well as a content area that should extend to the bottom of the page. However, I am facing some challenges in achieving this. Initially, I enclos ...

Ways to modify color while user moves the screen

I'm working with some jQuery code that changes the colors of elements as the user scrolls down, and I want it to revert back to the original color when scrolling back up. However, the script is not behaving as expected... Here is the original working ...

Guide on toggling mat-checkbox according to API feedback in Angular 6

Just starting out with angular 6 and I'm attempting to toggle the mat-checkbox based on the API response. However, I seem to be having trouble. All the checkboxes are showing as checked even when the API response is false. <div class="col-sm-12" ...

Guide on transferring state to activate a second Material UI tab upon clicking a Link within a React Next.js Application

Within my menu, there is a link structured like this: <ListItem button component="a" href="/messages" onClick={(e) => handleClick}> <ListItemText primary="Sent" /> </ListItem> The /messages route cont ...

Why does the ReactJS MaterialUI Modal fail to update properly?

Recently, I encountered a curious issue with my Modal component: https://i.stack.imgur.com/dkj4Q.png When I open the dropdown and select a field, it updates the state of the Object but fails to render it in the UI. Strangely, if I perform the same action ...