Building a Nested Navigation Menu in React

Introducing: React Nested Nav

Bret Morris
The Startup

--

React Nested Nav in action

Sites like Amazon and Aesop use nested navigation as a way to present a lot of information to users in a hierarchical way. Building navigation menus like this can be challenging, to say the least, but it seems clear that this UX pattern is effective since some of the largest companies in the world are utilizing it to structure their content.

In order to make this sort of pattern a bit simpler to develop, I’d like to introduce React Nested Nav:

Repo: https://github.com/UseAllFive/react-nested-nav
Demo: https://useallfive.github.io/react-nested-nav/

React Nested Nav offers a React component called NestedNav that you can easily add to any part of your site to inject a nested navigation menu. For example, you may want to add the nested nav into a sidebar that’s revealed when a hamburger is clicked. To that, your code might look something like this:

Example usage of NestedNav

Really, the only thing that you have to do is ensure that the menus data is formatted correctly. This prop contains all the data for creating the nested nav. In theory, your nested nav can have as many levels as you need. To understand how the menus data must be formatted, it may be instructive to look at the NestedNav propTypes:

PropTypes for NestedNav

The above outlines that menus is an object with a title and id and items property. items is an array of objects with a text, optional link and menu property, which is an object that repeats all the same properties just listed. In theory, there is no limit to the amount of nesting that one can do as defined by this recursive PropTypes definition. Here’s an example of what the data looks like as an object:

Data example for menus prop of NestedNav

Note that menu items can have a link property. Items with a link item will trigger the onLinkClick function that also is passed in as a prop to NestedNav. This is where you should handle any custom routing, etc.

Typically, the final step is adding your own styles. Each section of the NestedNav component should have classes that you can override in your own stylesheets. Feel free to make them your own.

As always, this is an early release and I’m sure future versions will be much more robust. Please feel free to leave comments in the form of issues or create pull request if you would like to contribute to the codebase. Hopefully, react-nested-nav will save you a bunch of development time as well as make the internet a more functional place.

--

--