Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 225

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 62k
Author
Asked: November 25, 20242024-11-25T09:00:08+00:00 2024-11-25T09:00:08+00:00

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

  • 62k

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


If you enjoy this tutorial, please give it a 💓, 🦄, or 🔖 and consider:

📬 signing up for my free weekly dev newsletter
🎥 subscribing to my free YouTube dev channel


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 
Enter fullscreen mode Exit fullscreen mode

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',       },     ],   }, ]; 
Enter fullscreen mode Exit fullscreen mode

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} /> 
Enter fullscreen mode Exit fullscreen mode

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>   ); } 
Enter fullscreen mode Exit fullscreen mode

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>   ); } 
Enter fullscreen mode Exit fullscreen mode

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>   ); } 
Enter fullscreen mode Exit fullscreen mode

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!

javascriptprogrammingreactwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 1
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.