11

Trying to do the following, but it's not working.

ReactDOM.render(
  <Router>
    <div className="route-wrapper">
      <Switch>
        <App>
          <Route exact path="/" component={HomePage} />
          <Route path="/user" component={UserPage} />
        </App>
        <Route component={Err404} />
      </Switch>
    </div>
  </Router>,
  document.getElementById('main')
)

As the documentation says only Route and Redirect elements are allowed inside a Switch element. How do I get this to work without explicitly wrapping HomePage and UserPage in App or having the error page wrapped by App?

Okinawa Terminal
  • 165
  • 1
  • 1
  • 7

1 Answers1

19

While I have begun developing a "Universal React app", where the first page load is done with server-side rendering, I faced similar problem as the React-Router had just updated to 4.0. You should consider restructuring you application something as given below:

ReactDOM.render(
  <Router>
    <div className="route-wrapper">
      <Switch>
        <Route path="/" component={App} />
        <Route component={Err404} />
      </Switch>
    </div>
  </Router>,
  document.getElementById('main')
)

Where the App component is refactored as following:

class App extends React.Component {
  render() {
    return <div>
      <Switch>
        <Route exact path="/" component={HomePage} />
        <Route exact path="/user" component={UserPage} />
      </Switch>
    </div>;
  }
}
Rahul Sethi
  • 340
  • 2
  • 4
  • 10
    Regarding this example: Is it even possible to reach the Err404 component? The first Route matches everything and loads the App component, in which case would the Err404 component loaded? It does not detect if no match was found in subsequent Switches, does it? – FelixZett Feb 20 '18 at 12:49
  • 1
    Agreed. I don't think this will work - the Err404 component will never render. – Overlook Motel Dec 31 '18 at 13:04
  • This looks like a potential solution: https://stackoverflow.com/questions/41474134/nested-routes-with-react-router-v4 – Overlook Motel Dec 31 '18 at 13:07
  • can i use `` with `` inside functional component, how to use? – Ashish Kamble Aug 12 '19 at 11:05