Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returned React-Router <Route> doesn't work in switch

I wrote my application in a very modular way in the way that each package (section of the application) is a package and the only thing i'm returning from each package is a <Route to="/dest" component="something" />.

The problem that i'm having right now is that, this method of returning are not really working in and that's how i tested it:

The initial setup was something like this :

<Switch>
 <Dashboard {...rest} />
 <Users {...rest} />
 <Quiz {...rest} />
</Switch>

And the Dashboard component is something like this :

...
return (
    <Route exact path="/" render={ props => (
      <Dashboard {...props} {...stuff} />
    )}/>
  )

and almost the same thing for User and Quiz components, which are directly being imported from their module packages.

when i run the application, i can access Dashboard & Users but Quiz is not being rendered. if i change the order and put quiz on top of <Users /> it will work. which means it only can render one after first exact route.

but instead, if i take all those code and write the Routes in the switch itself without referencing to another component, it works like a charm.

<Switch>
 <Route exact path="/" render={ props => (
  <div>demo</div>
 )}/>
 <Route path="/dashboard" render={ props => (
  <div>demo</div>
 )}/>
 <Route path="/users" render={ props => (
  <Users />
 )}/>
 <Route path="/quiz" component="Users"/>              
</Switch>

I've tried both component, and render in route, this one is just a sample

any suggestion on why is this happening ?

UPDATE 1

I haven't managed to figure out what the problem is and what's causing it, but i found a way around it by creating a component that returns a Switch and direct Routes as children. then i exported the Switch to my main app.

like image 493
BardZH Avatar asked Oct 16 '22 19:10

BardZH


1 Answers

<Switch>
  <Dashboard {...rest} />
  <Users {...rest} />
  <Quiz {...rest} />
</Switch>

This will not work because Switch expects Routes to be direct children. It cannot perform its logic on arbitrary wrapper components.

I not sure if that would work but you would have to directly export Route from the module:

Dashboard.js

export default (
  <Route exact path="/" render={ props => (
    <Dashboard {...props} /> 
  )}/>
)

but when you do something like this:

export default (stuff) => (
  <Route exact path="/" render={ props => (
     <Dashboard {...props} {...stuff} />
  )}/>
)

Notice that you are not exporting a Route but a functional component that renders Route.

I personally think that you should only export purely components to be rendered without Routes and leave that up to library consumer.

like image 110
Tomasz Mularczyk Avatar answered Oct 27 '22 11:10

Tomasz Mularczyk