Laurentiu Tibea
Laurentiu Tibea

Reputation: 67

<Route> inside map

I didn't find an answer for my problem so I have to post a question here. Why the <Route> component from the second map isn't working? It get the data but doesn't build the <Route> component. The <Route> from the first map works. Maybe it's an easy solution but I cannot find one.

const {genres} = this.state;
return(
<React.Fragment>
<Switch>
    {!_.isUndefined(genres) &&
        genres.map(g => {
            if(_.isEmpty(g.subgenres)) return <Route path={g.link} component={Page} key={g._id}/>;
            else g.subgenres.map(sub => <Route path={sub.link} component={Page} key={sub._id}/>);
        })
    }
</Switch>
</React.Fragment>
);

data structure example:

genres = [
    {
        "_id":"823710",
        "name":"Rock",
        "subgenres":[
            {
                "_id":"29033",
                "name":"Heavy Metal",
                "link":"/heavy-metal"
            },
            {
                ... other data ...
            }
        ],
        "link":""
    },
    {
        ... other data ...
    }
]

Thanks!

Upvotes: 1

Views: 50

Answers (1)

Tholle
Tholle

Reputation: 112887

You are not returning anything in the else branch. Add the return keyword and it should work as expected.

genres.map(g => {
  if (_.isEmpty(g.subgenres)) {
    return <Route path={g.link} component={Page} key={g._id} />;
  } else {
    return g.subgenres.map(sub => (
      <Route path={sub.link} component={Page} key={sub._id} />
    ));
  }
})

Upvotes: 1

Related Questions