TypeOfNaN

Creating a Recursive List Menu Any Number of Levels Deep in React

Nick Scialli
December 17, 2020

Recursion can be a tricky concept in programming. The challenge seems greater in a view library like React. Today, we’ll use recursion to create a menu any number of levels deep. Additionally, we’ll make it so we can toggle the display of children at any level. Ultimately, we will have something that looks like this:

menu

Getting Started

To get started, we can first define our menu structure. Importantly, recursion will only work if we can treat each level in the menu the same, meaning it should have the same structure all the way down. To accomplish this, we can decide that each menu item will have a title and an array of children. Each of those children will follow the same format, all the way down.

For this post, we’ll use the following menu structure:

- Item 1
  - Item 1.1
    - Item 1.1.1
  - Item 1.2
- Item 2
  - Item 2.1

And we can represent this as a JavaScript object with a consistent interface all the way down:

const menu = [
  {
    title: 'Item 1',
    children: [
      {
        title: 'Item 1.1',
        children: [
          {
            title: 'Item 1.1.1',
          },
        ],
      },
      {
        title: 'Item 1.2',
      },
    ],
  },
  {
    title: 'Item 2',
    children: [
      {
        title: 'Item 2.1',
      },
    ],
  },
];

Displaying the Top Level

Let’s display the top level of our menu. We’ll create a Menu component. This component will take our menu array as an argument. So wherever we want to render the menu, it’ll look something like this:

<Menu items={menu} />

Within the Menu component, we will map over each item in the menu array and displays each item title in a list item. All fairly rudimentary React so far!

function Menu({ items }) {
  return (
    <ul>
      {items.map((item) => (
        <li key={item.title}>{item.title}</li>
      ))}
    </ul>
  );
}

Now we have a two item array. Our next challenge is rendering the next level of children.

Displaying the Next Level (and the Next and the Next)

It turns out displaying the following levels recursively isn’t as much of a challenge as we might have feared! Since we designed our data structure to me consistent all the way down, we can simply pass an item’s children array to another Menu call if the children exist. Here’s what I mean!

function Menu({ items }) {
  return (
    <ul>
      {items.map(item => (
        <li key={item.title}>{item.title}
        {item.children && <Menu items={item.children}>}
        </li>
      ))}
    </ul>
  );
}

And it looks like this:

three level list

Great Scott! It already works. It turns out that, through some careful design, it doesn’t take much effort to recursively display things in React.

Toggling Menu Items

Our list can get unwieldy, so we’ll want to start it out collapsed all the way at the top level and give the user the ability to toggle the display of children using a + or - button. To do so, we can simply have each level of our menu remember the display state of any set of children.

For example, the top-level menu will have some state that knows whether to show the children for Item 1 and whether to show the children for Item 2.

Let’s implement this logic and discuss it a bit.

import React, { useState } from 'react';

function Menu({ items }) {
  const [displayChildren, setDisplayChildren] = useState({});

  return (
    <ul>
      {items.map((item) => {
        return (
          <li key={item.title}>
            {item.title}{' '}
            {item.children && (
              <button
                onClick={() => {
                  setDisplayChildren({
                    ...displayChildren,
                    [item.title]: !displayChildren[item.title],
                  });
                }}
              >
                {displayChildren[item.title] ? '-' : '+'}
              </button>
            )}
            {displayChildren[item.title] && item.children && <Menu items={item.children} />}
          </li>
        );
      })}
    </ul>
  );
}

When we start out, each of our Menu components will have a piece of state called displayChildren set to {}. If you click the + button next to Item 1 at the top level, the displayChildren state will now equal { "Item 1": true }. This will be how the stateful displayChildren object works at each level of our menu!

Wrapping Up

Hopefully this gives you some insight into working with recursion in React. With a little careful planning, we can work with recursive data structures in React with relative ease!

Nick Scialli

Nick Scialli is a senior UI engineer at Microsoft.

© 2024 Nick Scialli