1

In my App.js file, I have a few routes enclosed within the Switch. The components are rendered depending upon the route. However, there are some components that are always rendered irrespective of the route (wrapper and <Sidebar /> below).

// app.js
...
<Router>
  <Switch>
    <div class="wrapper">
      <Sidebar />
      <Route exact path="/" component={Home} />
      <Route exact path="/about" component={About} />
    </div>
      <Route component={NotFound} />
  </Switch>
</Router>
...

The problem is that the NotFound component is not being rendered because of wrapper and <Sidebar /> elements that are global on all routes. I have a couple of questions,

  1. How do I correctly show NotFound component on invalid routes while keeping wrapper and <Sidebar /> global?
  2. Is keeping wrapper and <Sidebar /> global an anti-pattern? If so, how are global components rendered in routes?

1 Answer 1

1

As documentations for <Switch/> component says,

All children of a should be or elements. Only the first child to match the current location will be rendered.

And also looking at the source code of <Switch> makes clear that it iterates thru all children, searching for path prop and match it to currect location. So if some children of <Switch> are not or , unexpected behavior will be.

To solve your task I suggest to wrap Home and About components with HOC, which will render additional required components. For example

export function WithSidebar(props) {
    return <div class="wrapper">
        <Sidebar />
        {props.render()}
    </div>
}

And use it in Route like

<Router>
  <Switch>
      <Route exact path="/" render={() => (<WithSidebar render={() => <Home />} />)} />
      <Route exact path="/about" render={() => (<WithSidebar render={() => <About />} />)} />
      <Route component={NotFound} />
  </Switch>
</Router>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.