How to make a switch with nested components in react router v4?

Good day to all!

I'm going through this tutorial. There is such a code there:

<Router history={browserHistory}>
<Route path='/' component={App}>
  <IndexRoute component={Home} />
  <Route path='admin' component={Admin} />
  <Route path='genre' component={Genre} />
</Route>
<Route path='*' component={NotFound} />

I'm trying to rewrite it to react router v4.

It turns out something like this:

<BrowserRouter>
<Switch>
  <App>
    <Route exact path='/' component={Home} />
    <Route path='/admin' component={Admin} />
    <Route path='/genre' component={Genre} />
  </App>
  <Route component={NotFound} />
</Switch>

This option does not display NotFound.

Tell me, please, what is the problem?

2 answers

Switch iterates through children and stops the search when the desired route is found. You have two nodes in the Switch... In general, you need to remove the App wrapper. If you need to wrap some pages in the App, you can do this:

// high order component
// генерирует компонент, который оборачивает исходный в App
const withAppLayout = Component => props => <App><Component {...props} /></App>

<Switch>
  <Route exact path='/' component={withAppLayout(Home)} />
  <Route path='/admin' component={withAppLayout(Admin)} />
  ...
</Switch>

You can create a custom Route:

const AppRoute = ({ component, ...props }) => (
  <Route {...props} component={withAppLayout(component)} />
);

<Switch>
  <AppRoute exact path='/' component={Home} />
  <AppRoute path='/admin' component={Admin} />
  ...
</Switch>
 3
Author: alexes, 2017-06-27 13:14:33

I got this

const LoginLayout = ({ ...rest }) => {
  return (
    <Fragment>
      <img src={logo} className="logo" alt="logo" />

      <div className="login-container">
        <div className="left-side">
          <ToastContainer className="toaster" />
          <Switch>
            <Route path="/login/reset" component={ResetPassword} />
            <Route path="/login/password_reset" component={NewPassword} />
            <Route path="/login" component={Login} />
          </Switch>
        </div>
      </div>
    </Fragment>
  );
};

export default ({ childProps }) => (
  <Switch>
    <LoginLayout path="/login" component={LoginLayout} />
    <PrivateRoute path="/" exact name="Home" component={DefaultLayout} />
  </Switch>
);

Routing works, but it seems that the wrong approach. could the experts correct it?

 0
Author: kuka, 2019-02-19 13:04:58