Slowl
Slowl

Reputation: 3

Render components from an array of object

I have an array of object, containing another array of object like this :

[{label: "Commons",
  path: "commons",
  component: Commons,
  subroutes: [
  {
    label: "Commons doc",
    path: "commons/doc",
    component: CommonsDoc,
  }]
 }]

Then I pass it as a prop to a component, and map the prop to render in React the first level component "Commons" with this in another bloc :

<StyledRouter>
    {routes.map((route, index) => (
        <route.component path={route.path} key={index} />
    ))}
</StyledRouter>

I'm using Reach Router for React, and now I'm trying to render the second level component at subroutes, using a second map function right under the first <route.component path={route.path} key={index} />

But I can't get it work like this {route.subroutes.map(...)} to render the CommonsDoc component in my second array of object

Upvotes: 0

Views: 452

Answers (3)

Mohith
Mohith

Reputation: 115

Something like this should help you:

const composeRoutes = (routes) => {
    allRoutes = routes.map((route, index) => {
        if (route.subroutes.length > 0) {
            let withSubRoutes = [];
            withSubRoutes = composeRoutes(route.subroutes);
            withSubRoutes.append(<route.component path={route.path} key={index} />);
            return withSubRoutes;
        }
        return <route.component path={route.path} key={index} />;
    })
    return _.flatten(allRoutes);
};
<StyledRouter>
    {composeRoutes(routes)}
</StyledRouter>

Upvotes: 0

abrahims
abrahims

Reputation: 16

To create a dynamic tag name in JSX you need to assign the name value to a capitalized variable

<StyledRouter>
   {routes.map((route, index) => {
     const Route = route.component;
     return (<Route path={route.path} key={index} />)
   })}
</StyledRouter>

and you should do the same thing for subroutes

Upvotes: 0

user10269409
user10269409

Reputation:

If I get the question right, you should map it like that:

routes.map(route => route.subroutes).map(subroute => 'do whatever you want with each subroute')

Upvotes: 1

Related Questions