React JS – Infinite Sub Menu

I’m going to mention right off the bat this tutorial doesn’t end with you having a ready to use menu. BUT.. it shows you a simple concept you can use to create the elements necessary for the old school infinite sub menus.

Infinite Sub Menus Were All the Rage

It’s been quite some time since I’ve seen infinite menus used. Maybe it’s because people are becoming more mobile conscious in their design decisions. The only way I could see infinite sub menus be mobile friendly is if the sub menu completely replaced the previous one.

It’ll probably seem ridiculously obvious once you see the solution but it may come in handy in the future. Here are two React components; List and ListItem, that can be used to accomplish infinite sub menus.

The Components

 

 

Notice the second import statement. My components are in a directory structure as follows:
-components
–List
—index.js
—List.js
–ListItem
—index.js
—ListItem.js

Because I’m a sucker for modular organization even with simple examples.

Now for the ListItem component:

 

 

Basically the solution comes down to the line
{ items && <List items={items} />}.

We’ve created sort of a circular dependency where a List, has ListItems, which can potentially contain another list. If you’re not sure what’s happening, React is looking at the items variable, if it does not equal undefined, it will continue to the other half of the AND (&&) comparison displaying a new list.

This is also true for vanilla JavaScript. If the first half of an AND comparison fails it will not bother with the rest.

Finally, I’ll give you a quick example object passed to the List component.

That’s all there is to it. Let me know if you have any issues with the following code.

Leave a Reply

Your email address will not be published. Required fields are marked *