Back to all articles

A slidedown menu in React

A while ago I was working on a new project. It was developed in React, which I was completely new to at the time. Part of my job was to figure out how to translate some nice designs into components. I had just created a dropdown menu and I wanted to add a final touch: a CSS animation to make it slide down.

This was a new puzzle for me because things in React work a bit differently. Components aren’t always in the DOM, they come into existence and disappear on demand. Of course, I wasn’t going to reinvent the wheel, I searched the web. I didn’t find a ready-to-use solution for a slidedown effect in particular, but some articles and examples pointed me in the right direction. Soon I was able to work it out, pretty happy with the result.

Let me show you step by step, and if you just want the final solution, you’ll find it at the end.

Say you’ve got a menu component with a nested submenu, which for now is simply shown and hidden with CSS:

Firstly, you want the component to mount and unmount depending on the state, instead of controlling this behavior with styles:

Note how handlers showing and hiding the submenu are attached to onMouseEnter and onMouseLeave events. These are not browser events but cross-browser React wrappers called SyntheticEvents.

We’ve got onMouseLeave on the parent <li> element because we want the submenu to stay open when we navigate to the submenu options.

Now that we’ve got this working, we can add the transition, using a React Add-on called CSSTransitionGroup.

Wrapping a component in a CSSTransitionGroup adds and exposes to you some possible extra transition phases: appear, enter, and leave. It applies pairs of class names during those phases. This gives you an easy way to apply basic CSS animations when the component enters and leaves the DOM. You can control the class names and the durations of transitions by passing specific props to the CSSTransitionGroup component.

If you want to learn more, there’s very good documentation explaining the React Transition Group library in detail available on reactcommunity.org and reactjs.org.

If you’re not familiar with CSS transitions yet, you can learn about them on MDN web docs. Be sure to check how to keep your animations cheap and smooth.

Note how I wrapped the transitioned submenu in a container to constrain it and control the starting point of the animation. You can comment out the styles for the container (.submenu-container) to see the state of affairs before doing this.

Feel free to copy this code and use it however you want. With each component you want to slide, you’ll probably need a different container class to tweak it to your particular needs.

I hope you found this helpful!

Here are two other cool uses of CSSTransitionGroup that might interest you: removing an item with a slide effect and sliding components in and out.

Share this article: