Creating a dropdown navigation menu

I am trying to create a smooth slide down menu effect, but it seems to instantly expand with no transition. Can anyone help me troubleshoot this issue?

const Container = styled.section`
  position: relative;
  overflow: hidden;
`

const WrapperItems = styled.div`
  padding-left: 2rem;
  user-select: none;
  transition: all 1s ease-in-out;
  position: relative;
  height: 0;

  &.active {
    max-height: 100vh;
    height: auto;
  }

return (
    <Container>
      <Wrapper onClick={() => setIsOpen(!isOpen)}>
        <div className="title">{title}</div>

      </Wrapper>
      <WrapperItems className={isOpen ? "active" : ""}>
        {items.map(item => (
          <div className="item" onClick={() => navigate(item.to)}>{item.title}</div>
        ))}
      </WrapperItems>
    </Container>
  );

Answer №1

Creative CSS solutions

Regrettably, CSS does not allow for transitions on an auto value due to performance concerns.

One workaround is to replace auto with a fixed value like 500px.

Another alternative is to utilize a "hack" by animating the max-height property to a value higher than the content's actual height. However, the challenge lies in finding a value that is not too high to avoid a delay in collapsing the non-visible part of the items wrapper.

padding-left: 2rem;
user-select: none;
transition: all 1s ease-in-out;
position: relative;
max-height: 0;

&.active {
  max-height: 30vh; /* ensuring content never exceeds 30 vh */
}

Innovative JavaScript solutions

JavaScript offers effective solutions as well.

For instance, using framer motion allows for utilizing the height: auto syntax:

import { motion } from "framer-motion";

// [...]

return (
  <Container>
    <Wrapper onClick={() => setIsOpen(!isOpen)}>
      <div className="title">{title}</div>
    </Wrapper>
    <WrapperItems>
      <motion.div
        animate={isOpen ? "open" : "closed"}
        variants={{
          open: { height: "auto" },
          closed: { height: 0 },
        }}
      >
        {items.map((item) => (
          <div className="item" onClick={() => navigate(item.to)}>
            {item.title}
          </div>
        ))}
      </motion.div>
    </WrapperItems>
  </Container>
);

// [...]

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

Creating Child Components Dynamically using String Names in ReactJS

I've encountered an issue with dynamically rendering React Components within my DashboardInterface component. I have an array filled with string names of React Components, retrieved through an external mechanism. The goal is to render these Components ...

The data integrity was compromised at /notes/add due to a failure in the NOT NULL constraint for the created field

Having encountered an issue while trying to execute the add function in Django2, I am unable to create a new post. The error message is as follows: IntegrityError at /notes/add NOT NULL constraint failed: notes_note.created Please find the views below: ...

Tips for automatically setting Material UI checkbox list as checked by default

Is there a way to have all items checked by default when the component first renders? I've tried using the defaultChecked property from the docs, but setting it to true didn't work. The checked property also does not seem to have any effect. Yo ...

using the useEffect hook to create a loop that runs infinitely

For my project, I am working on updating data in firebase. The issue that I'm facing is that the data seems to be constantly looping, causing potential crashes. Is there a way to stop this loop and prevent any crashing? import "./App.css"; ...

Is Dotenv-webpack suitable for use in a production environment?

Trying to utilize the dotenv-webpack plugin has been a smooth process locally. However, when it comes to deploying to Heroku, issues arise. Even after following suggestions from this GitHub issue, difficulties persist. The webpack configuration I am usin ...

What is the best way to integrate a PHP page with its own CSS and JavaScript into a Wordpress page?

I'm facing a challenge with integrating a dynamic PHP table into my WordPress page. Despite working perfectly when opened locally, the CSS and JavaScript used to create the table are not functioning properly when included in a WordPress page via short ...

Changing the URI in accordance with the previous URI

I am encountering an issue in my React application where multiple updates of the URI are being made within the same event by adding query parameters using the router.push function from various locations in the code. However, some updates are getting lost b ...

Tips on how to stop a webpage from scrolling and instead allow only the inner content to scroll

Check out my plunker for reference. The goal I am aiming for is as follows: The webpage should stay fixed and not scroll in any direction If the content overflows its container, a scroll bar should appear strictly within that container I have a main co ...

Display updated text on hover over button panel

Is it possible to achieve the following using only CSS without any JavaScript? The desired outcome is a div containing two font awesome icons aligned to the right side. Specifically, I am looking for: - Icon of a pen that reacts on mouse hover - Icon o ...

When a Grid Item is enclosed in a link, it does not extend over rows

After avoiding HTML/CSS for a long time, I finally decided to dive in and create a simple CSS grid website with 3 items in the grid. Everything was working well and looking exactly as I wanted it to: https://i.sstatic.net/zVQ9U.jpg However, I had the ide ...

How can you invoke a component method from a different component in a react-redux setup?

Currently in the process of developing a React Native app that features an audio player. This audio player will have its own view with controls such as Play, Stop, and Skip. The challenge I am facing is ensuring that this audio player can be controlled fro ...

Discovering the capabilities of heic2any in a Next.js client-side environment

Here is the code snippet: import convert from 'heic2any' try { convertedImage = await convert({ blob: propsAndFile?.file }) } catch (error) { console.error(error) } Encountered an error while trying to run this code on the client side, ...

What sets apart utilizing useInfiniteQuery compared to the usage of QueryClientProvider in React Query?

Recently, I've been grappling with a dilemma surrounding the best practices for utilizing QueryClientProvider and useInfiniteQuery. I found myself using the useInfiniteQuery function as a global state across certain rendered components. However, I enc ...

Ways to extend the waiting timeout from 30000 ms to 60000 ms for npm installation on Ubuntu

Due to the slow internet connection, I was unable to install packages from npm. The issue arose when npm returned an error stating: npm ERR! Response timeout while trying to fetch https://registry.npmjs.org/create-react-app (over 30000ms) I thought tha ...

The interaction of a horizontal scroll bar on a CSS Grid layout triggers the appearance of a vertical scroll bar

I am facing a challenge with my HTML layout. In Chrome, when the horizontal scroll bar is visible, a vertical scroll bar also appears. However, in Firefox, everything works fine. This issue seems to be related to the height of the div not auto-scaling prop ...

Ways to pinpoint a particular division and switch its class on and off?

Consider this scenario, where a menu is presented: function toggleHiddenContent(tabClass) { let t = document.querySelectorAll(tabClass); for(var i = 0; i<t.length; i++) { t[i].classList.toggle="visible-class"; } } .hidden-conten ...

White space in Bootstrap 4 grid caused by a full-width row

I have set up a bootstrap grid layout that includes ads, and I wanted to integrate a section for banners within it. After some experimentation, I managed to achieve this by inserting a container between the ads and the banners, each housed in their own row ...

The -moz-use-text-color property does not function properly in Chrome and IE versions 9 and above

I have added -moz-use-text-color for border-color in the following CSS code: .booksline{ border-image: none; margin: 0 auto 0px; width: 96%; height:220px; padding:20px 20px 20px 0; border-width: 1px 1px medium; border-style: solid solid none; border-colo ...

What is the mechanism through which a nested function within an event handler obtains the event object?

How is the e object available to the nested function inside handleClick2 when only the input object is passed? Is this related to the concept of Lexical Environment? handleClick2 = (input) => (e) => { this.setState({ [input]: e.target.va ...

Select the five previous siblings in reverse order using jQuery's slice method

I have a unique approach to displaying a series of divs where only 5 are shown at a time using the slice() method. To navigate through the items, I include an ellipsis (...) link after every 4th item, which allows users to easily move on to the next set of ...