React-router: Custom route in `<Switch/>` v4 doesn't seem to work

Created on 22 Feb 2017  路  4Comments  路  Source: ReactTraining/react-router

Version

"react-router-dom": "^4.0.0-beta.5"

Test Case

import { Switch, Route } from 'react-router-dom'

const Foo = () => <Route path="/" component={Home}/>

<Switch>
  <Foo/>
</Switch>

Expected Behavior

Should behave like this:

import { Switch, Route } from 'react-router-dom'

<Switch>
  <Route path="/" component={Home}/>
</Switch>

Actual Behavior

It looks like nothing is rendered?

(Note: Is there any jsfiddle/jsbin template for v4? Only found v2.)

Most helpful comment

It is possible to create custom routes in a different way:

// to get started with ts
import { Switch, Route } from 'react-router-dom'

export const Route: new (props?: any, context?: any) => React.Component<any, any>;

export class Foo extends Route {
  static defaultProps = {
    path: '/',
    component: Home
  };
}

// works now
<Switch>
  <Foo/>
</Switch>

Man.... How I wish react-router would be written in TypeScript :)

All 4 comments

Custom routes passed to a <Switch> are not supported. You can get them to work by giving them the correct props (check out the <Switch> source to see how it works), but you can't just pass any element that renders a <Route> to a <Switch>.

It is possible to create custom routes in a different way:

// to get started with ts
import { Switch, Route } from 'react-router-dom'

export const Route: new (props?: any, context?: any) => React.Component<any, any>;

export class Foo extends Route {
  static defaultProps = {
    path: '/',
    component: Home
  };
}

// works now
<Switch>
  <Foo/>
</Switch>

Man.... How I wish react-router would be written in TypeScript :)

Inside of a <Switch>, the components are just used for their props. A custom route needs to have the correct props to be matched (path, possibly location, exact or strict). If it has those, it can work, it just isn't supported.

Hmm. I have seen examples that do work with exactly the OP pattern. Exactly what is the use of a Switch if I can't pass a custom Route to it? What makes the Route custom is embedded but not so if I do the extra typing to wrap it up as an extension of Route? Something seems wrong about this reading the above. Am I missing something? At the least the suggested working fix looks clumsy.

Was this page helpful?
0 / 5 - 0 ratings