0

Disclaimer... this might turn into more of a specific js question (relating to dynamically accessing object properties using variables) ...

I am attempting to create a dynamically rendered menu where a menu schema is passed in (testinputs) and that menu is rendered complete with routing.

There are two parts to this:

  1. rendering the menu itself

  2. rending the routes

This question is about rendering the routes.

import DataGrid from "./DataGrid.js"
import AddItem from "./AddItem.js"

const AllMenuItems = {
  "DataGrid":DataGrid
  "AddItem":AddItem,
}

const testinput = {
  data: [
    {
      name: "DataGrid",
      url: "/datagrid",
    },
    {
      name: "Transact",
      children: [
        {
          name: "AddItem",
          url: "/additem",
        },
      ],
    },
  ],
};

I have a function expression that utilizes jsx to return a specific dynamic route...

Rendering works when I hard code the component prop like so, referencing the imported React component directly...

<Route path={url} component={AddItem}/>

But when I attempt to do things dynamically (see below) the routing doesn't work.

const routeBuilder = (children) => {
    return children.map((subOption) => {
      if (!subOption.children) {
        var name = subOption.name;
        var url = subOption[url];
        var MyComponent = AllMenuItems[name];    
        return (
          <Route path={url} component={MyComponent}/>
        );
      }
      routeBuilder(subOption.children);
    })
  }

What am I overlooking here? Thanks in advance.

1 Answer 1

1

One issue is recursive routeBuilder return values are not used.

Some thing like

const routeBuilder = (children) => {
    return children.map((subOption) => {
      if (!subOption.children) {
        var name = subOption.name;
        var url = subOption[url];
        var MyComponent = AllMenuItems[name];    
        return (
          <Route path={url} component={MyComponent}/>
        );
      } else {
         return routeBuilder(subOption.children);
        }
    })
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Ah. That would be the issue. I have another recursive menuBuilder function that handles the recursive case correctly but when I created routeBuilder, the proper handling of the recursive case got lost in the translation somewhere. Simple mistake and overlooking. Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.