Search code examples
javascriptbootstrap-4user-permissionsuser-rolessession-storage

How to display menu items based on sessionStorage


I'm kind of lost in which is the best way to proceed. After fetching the user data from an API, I store the user data in the sessionStorage. How can I display menu items based on roles (ie- Admin, Representative, Guest).

I have a basic Bootstrap Sidebar that looks like below.

<ul class="sidebar-nav">
 <li><a>Home</a>
   <ul class="sidebar-dropdown">
     <li>Default</li>
     <li>Reports</li>
   </ul>
 </li>
 <li><a>Contact</a>
    <ul class="sidebar-dropdown">
      <li>Admin Contact</li>
      <li>Contact 1</li>
    </ul>
 </li>
</ul>

Should I add classes to menu items based on roles to my menu items and with a JavaScript function that runs on load display or hide menu items??

Any guidance would be greatly appreciated.

JSFIDDLE


Solution

  • What you want is dynamically render a list based on data. Receiving data from session storage is not an issue because it can be done by

    JSON.parse(sessionStorage.getItem('data'));
    

    your issue is to render them. Try to use hardcoded data first to see if you are able to render what you want and then just plug in data from the storage. For an example https://codesandbox.io/s/elated-fast-my3ud?file=/src/index.js

    const routes = [
      {
        href: "/home",
        title: "Home",
        children: [
          {
            href: "/home/defaults",
            title: "Defaults"
          },
          {
            href: "/home/reports",
            title: "Reports"
          }
        ]
      },
      {
        href: "/contact",
        title: "Contact",
        children: [
          {
            href: "/contact/admin-contact",
            title: "Admin Contanct"
          },
          {
            href: "/contact/contact-1",
            title: "Contact 1"
          }
        ]
      }
    ];
    
    function renderSingleRoute(route) {
      const children = route.children ? renderRoutes(route.children) : "";
      return `
        <li>
          <a href="${route.href}">${route.title}</a>
          ${children}
        </li>
      `;
    }
    
    function renderRoutes(routes) {
      return `
        <ul>
          ${routes.map((route) => renderRoute(route)).join("")}
        </ul>
      `;
    }
    
    document.getElementById("app").innerHTML = renderRoutes(routes);
    

    So the idea here is to build your routes however you want and then pass it to render function