I have routes objects from backend and set it to routes like this and when I am set NotFound component, which route is ‘*’ to default in switch/case or to case “NotFound” which commented now, it all the time show with all components after them.
I mean it works all the time, not just in the wrong URL way
JavaScript
x
36
36
1
function getProperComponentData(el) {
2
switch (el.label) {
3
case "Home":
4
return { el, exact: true, Component: Home };
5
case "Categories":
6
return { el, Component: Categories };
7
case "Popular":
8
return { el, Component: Popular };
9
case "Movies-by-Categorie":
10
return { el, Component: MoviesByCategory };
11
case "Asset":
12
return { el, Component: AssetDetails };
13
case "Discover":
14
return { el, Component: Discover };
15
// case "NotFound":
16
// return { ...el, Component: NotFound };
17
default:
18
return { el, Component: NotFound };
19
}
20
}
21
22
const RoutesApp = ({ routes }) => {
23
if (routes) {
24
const array = routes.map((el) => {
25
const { id, exact, route, Component } = getProperComponentData(el);
26
return (
27
<Route key={id} exact={exact} path={route} component={Component} />
28
);
29
});
30
31
return array;
32
}
33
34
return null;
35
};
36
I’ve already tried a lot.. Even delete not-found route from backend object, and set it manually to Router like this
JavaScript
1
11
11
1
<Router>
2
<NavBar menu={this.state.menu ? this.state.menu : false} />
3
4
<Switch>
5
<RoutesApp
6
routes={this.state.routes ? this.state.routes : false}
7
/>
8
<Route path="*" component={NotFound} /> // here I set it manually but delete from routes at line above (this way it's not working at all)
9
</Switch>
10
</Router>
11
But in this way at totally not work
Any ideas? it shows all the time
Advertisement
Answer
That occurs because all children of a <Switch>
should be <Route>
or <Redirect>
elements.
You can check more about it in react-router-dom docs.
So, one solution for your code would be do something like that:
JavaScript
1
16
16
1
// I've just removed `RoutesApp` and rendered .map directly
2
<Switch>
3
{this.state.routes && this.state.routes.map((el) => {
4
const { id, exact, route, Component } = getProperComponentData(el);
5
return (
6
<Route
7
key={id}
8
exact={exact}
9
path={route}
10
component={Component}
11
/>
12
);
13
})}
14
<Route path="*" component={NotFound} />
15
</Switch>
16