A
A
Anton Filippov2019-03-24 08:22:08
React
Anton Filippov, 2019-03-24 08:22:08

How do you render components depending on the route?

Asked a similar question on StackOverflow , got some interesting answers. But interested in the practical experience of developers.
In short - periodically there is a task to render some component (header, footer, sidebar, whatever) only on some routes. Let's say there are 100 routes in the application, 50 of them should have a header, 50 should not.
As suggestions, I received options:
1) Use HOC
2) Here is the following construction:

...
<Switch>
  <Route path="/noheader1" ... />
  <Route path="/noheader2" ... />
  <Route path="/noheader3" ... />
  <Route component={HeaderRoutes} />
</Switch>
...

HeaderRoutes = props => (
  <React.Fragment>
    <Header/>
    <Switch>
      <Route path="/withheader1" ... />
      <Route path="/withheader2" ... />
      <Route path="/withheader3" ... />
    </Switch>
  </React.Fragment>
)

In principle, both are suitable, but each has its own nuances. And what if we add consideration not only for the header, but also for the footer, and suddenly their common routes do not intersect?
I'm more interested in practical experience, do you have such situations and how do you resolve them? Or just don't worry about DRY and shove the header into every component where it's needed?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Robur, 2019-03-24
@Robur

<Route path="/iwantrenderonthis" component={MyComponent} />

If the path does not suit you, you can complicate the matching up to your custom one, but the essence is the same. HOC is pretty handy.
and this can be put anywhere in the application, if the route matches - MyComponent is rendered, if not, then not.
ReactRouter v4, maybe it was more difficult in the past, I don’t remember.
Perhaps the hooks will make it more beautiful, I have not tried it.

S
Sergey Suntsev, 2019-03-26
@GreyCrew

In terms of practical implementation, I would slightly overload the routes (in fact, they have to be overloaded for the visibility area)
Then you can wrap it in a Redux container and, according to some (only you know) condition, send a visibility parameter to it, depending on which you can render or do not render some component

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question