I attempted to implement a CSS and Typescript animation for a sliding effect, but unfortunately, it isn't functioning

So I'm encountering an issue with this unique ts code:

{/* Mobile Menu */}
        <div className="lg:hidden">
          <button className="flex items-center w-8" onClick={toggleMenu}>
            {isMobileMenuOpen ? (
              <button className="w-full h-full">
                <AiOutlineUp className="w-full h-full" />
              </button>
            ) : (
              <button className="w-full h-full">
                <AiOutlineDown className="w-full h-full" />
              </button>
            )}
          </button>
        </div>
        {/* Desktop Menu */}
        <div className="hidden lg:block">
          <ul className="flex flex-row gap-8 text-[22px]">
            {renderNavLinks(navLinks)}
          </ul>
        </div>
      </div>
      {/* Mobile Menu Items */}
      <div
        className={`mobileMenu lg:hidden p-10 bg-[#101010] ${
          isMobileMenuOpen ? "selected" : "dismiss"
        }`}
      >
        {isMobileMenuOpen && (
          <ul className="flex flex-col gap-4 text-[22px]">
            {renderNavLinks(navLinks)}
          </ul>
        )}
      </div>

Moreover, I have implemented a standard css with slide-in and slide-out keyframe animations. Surprisingly, it is functioning perfectly when I open the mobile menu button. However, when I try to close it, the animation somehow fails to work as expected. Instead, it abruptly jumps to the closed state without any transition. I've attempted various potential solutions such as modifying the animation using transform or employing a timeout handler; however, none of them seem to resolve the issue. Do you have any suggestions or ideas on how I can possibly solve this problem?

Answer №1

Here's a unique solution for you.

import { useState, useEffect } from 'react';

const ResponsiveMenu = ({ menuItems }) => {
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const mobileMenuRef = useRef(null);

  const toggleMenu = () => {
    setIsMobileMenuOpen(!isMobileMenuOpen);
  };

  const closeMenu = () => {
    const menu = mobileMenuRef.current;
    menu.addEventListener('animationend', () => {
      setIsMobileMenuOpen(false);
    }, { once: true });
    menu.classList.add('slideout');
  };

  const renderMenuItems = (menuItems) => {
    return menuItems.map((item) => (
      <li key={item.id}>
        <a href={item.link}>{item.label}</a>
      </li>
    ));
  };

  useEffect(() => {
    // Some additional functionality can be added here
    console.log("Responsive Menu Component is rendered.")
  }, []);

  return (
    <div className="responsive-menu">
      {/* Mobile Menu */}
      <div className="lg:hidden">
        <button className="menu-toggle-btn" onClick={toggleMenu}>
          {isMobileMenuOpen ? (
            <button className="arrow-up-btn">
              <i className="fa fa-arrow-up" />
            </button>
          ) : (
            <button className="arrow-down-btn">
              <i className="fa fa-arrow-down" />
            </button>
          )}
        </button>
      </div>
      {/* Desktop Menu */}
      <div className="hidden lg:block">
        <ul className="desktop-menu">
          {renderMenuItems(menuItems)}
        </ul>
      </div>
      {/* Mobile Menu Items */}
      <div
        className={`mobile-menu lg:hidden ${
          isMobileMenuOpen ? "animate-slidein selected" : "animate-slideout dismiss"
        }`}
        ref={mobileMenuRef}
      >
        {isMobileMenuOpen && (
          <ul className="mobile-menu-items">
            {renderMenuItems(menuItems)}
          </ul>
        )}
        {isMobileMenuOpen && (
          <button className="close-btn" onClick={closeMenu}>
            <i className="fa fa-times" />
          </button>
        )}
      </div>
    </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

Converting a JavaScript function to work in TypeScript: a step-by-step guide

When writing it like this, using the this keyword is not possible. LoadDrawing(drawing_name) { this.glg.LoadWidgetFromURL(drawing_name, null, this.LoadCB,drawing_name); } LoadCB(drawing, drawing_name) { if (drawing == null) { return; ...

Troubleshooting issues with media queries related to device pixel ratio

My media queries in LESS are functioning correctly on the desktop, but encountering issues when tested on an iPad2 or Samsung Galaxy 4 phone. It appears that the device-pixel-ratio is causing disruptions. I attempted to reduce the min-device-pixel-ratio to ...

Tips on combining react material ui Link and react router Link for seamless integration

My navigation bar has a routing issue that I'm trying to solve. Currently, the router only responds when the route is manually typed in the search bar. Clicking on the tabs does not redirect properly, except for the home button tab. import React from ...

How can I implement a feature in React.js where clicking a button triggers a Canvas to draw something?

I am trying to implement a <button> component that will trigger a specific function to draw on my HTML5 Canvas element. This is how the project files are structured and how I have passed the necessary props -> The main drawing function is locate ...

Creating a script to open multiple URLs in HTML and JavaScript

Currently, I am working on creating a multiple URL opener using HTML and JavaScript. However, I have encountered an issue where HTTP links are opening fine but HTTPS links are not. Can someone provide assistance with this problem? Below is the code snippet ...

In Deno, it is possible to confirm that a variable is an instance of a String

I'm having trouble asserting instances of string in Deno: import { assertInstanceOf } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2642405050405e445e59445e">[email protected]</a& ...

Issue encountered when submitting form: Error identified as "Unexpected string expression without template curly in string"

As a novice in React.js, I am facing an issue where setState is not functioning properly when submitting a form. Any suggestions on how to resolve this problem? > class Home extends Component{ constructor(props){ > super(props) > ...

The responsive menu refuses to appear

my code is located below Link to my CodePen project I'm specifically focusing on the mobile view of the website. Please resize your screen until you see the layout that I'm referring to. I suspect there might be an issue with my JavaScript cod ...

Tips on updating primeng Panel Menu appearance with scss

I'm looking to customize the color of my panel menu to black. Below is the HTML code I am using. <p-panelMenu styleClass="font-bold text-xs m-0 w-11" [model]="items" [multiple]='false'></p-panelMenu> ...

Securing paths using Next.js and Express

Currently, I'm in the process of developing an application with NextJS, Firebase Authentication, and Express. When a user signs up or signs in, Firebase sends me a token that I can use to verify the user and protect certain routes within the app. c ...

Looking for a solution to resolve the issue "ERROR TypeError: Cannot set property 'id' of undefined"?

Whenever I attempt to call getHistoryData() from the HTML, an error message "ERROR TypeError: Cannot set property 'id' of undefined" appears. export class Data { id : string ; fromTime : any ; toTime : any ; deviceType : string ...

The certificate leaf_signature is not being recognized by Node

npm ERR! errno UNABLE_TO_VERIFY_LEAF_SIGNATURE npm ERR! request to https://registry.npmjs.org/cra-template failed, reason: unable to verify the first certificate I encountered this issue while attempting to run commands like npx create-react-app ./ or npm ...

Obtaining Data from a Database Using Angular

I have developed a front-end website using Angular as my framework, integrated with node.js. To interact with the database, I created a "server.ts" file and connected it successfully to my DB. Now, my goal is to fetch data from the database and display i ...

The customization feature in Mui v5 is unable to implement the color specified in the

I have created a custom theme in MUI V5 as shown below: import React from "react"; import { createTheme, Theme } from "@mui/material/styles"; import { brown, red } from "@mui/material/colors"; export const theme = creat ...

Discovering the children of the target DOM element in React

Imagine you have an HTML unordered list that you want to turn into a React element: <ul id="mylist"> <li><a href="">Something</a></li> <li><a href="">Another thing</a></li> <li><a ...

The problem with clearing floats in IE7 (as well as 6)

Currently, I am facing an issue where I have a list that I want to split into three columns by using the float left property and then clearing the first column. Everything seems to be working fine in IE8 and FF, however, IE7 is causing the second column t ...

Trouble arises with the MUI 5 date picker when inputFormat is included

When I select a date from the calendar, everything works fine. However, if I set inputFormat="yyyy/MM/dd" and manually type in the date, it doesn't recognize the date format properly. Instead, it treats the input as a string like 11111111111 ...

Jest - verifying the invocation of local storage within an async function that is currently being mocked

I need assistance with testing an API call within a React component. The current setup involves setting localStorage in the api call, which is causing issues when trying to test if it's being called correctly. login = () => { // <--- If I se ...

Using Typescript with Styled-Components and Styled-System: Unable to find a matching overload for this function call

Encountering the infamous "No overload matches this call" error when using a combination of Typescript, Styled-Components, and Styled-System. I've come across solutions that suggest passing a generic type/interface to the styled component, like the o ...

Issue with blur event for Select component in MUI DataGridPro / DataGridPremium during header rendering

Encountering an error triggered by the onBlur event while rendering a <Select /> component in a column header of either a <DataGridPro /> or <DataGridPremium />: Failed to execute 'contains' on 'Node': parameter 1 is n ...