Skip to content
Advertisement

React router always showing NotFound component

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

function getProperComponentData(el) {
  switch (el.label) {
    case "Home":
      return { ...el, exact: true, Component: Home };
    case "Categories":
      return { ...el, Component: Categories };
    case "Popular":
      return { ...el, Component: Popular };
    case "Movies-by-Categorie":
      return { ...el, Component: MoviesByCategory };
    case "Asset":
      return { ...el, Component: AssetDetails };
    case "Discover":
      return { ...el, Component: Discover };
    // case "NotFound":
    //   return { ...el, Component: NotFound };
    default:
      return { ...el, Component: NotFound };
  }
}

const RoutesApp = ({ routes }) => {
  if (routes) {
    const array = routes.map((el) => {
      const { id, exact, route, Component } = getProperComponentData(el);
      return (
        <Route key={id} exact={exact} path={route} component={Component} />
      );
    });

    return array;
  }

  return null;
};

I’ve already tried a lot.. Even delete not-found route from backend object, and set it manually to Router like this

        <Router>
            <NavBar menu={this.state.menu ? this.state.menu : false} />

            <Switch>
              <RoutesApp
                routes={this.state.routes ? this.state.routes : false}
              />
              <Route path="*" component={NotFound} /> // here I set it manually but delete from routes at line above (this way it's not working at all)
            </Switch>
          </Router>

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:

 // I've just removed `RoutesApp` and rendered .map directly
 <Switch>
   {this.state.routes && this.state.routes.map((el) => {
     const { id, exact, route, Component } = getProperComponentData(el);
     return (
       <Route
         key={id}
         exact={exact}
         path={route}
         component={Component}
       />
     );
   })}
   <Route path="*" component={NotFound} />
 </Switch>
Advertisement