Home > database >  Add a component as props inside a Route with react-router-dom
Add a component as props inside a Route with react-router-dom

Time:11-17

Having the following code:

import { Switch, Route, BrowserRouter as Router } from 'react-router-dom';

export function MyComponent({ list }: MyComponentProps) {
  return (
    <Router>
      <Switch>
        <Route path={list[0].url} component={<NextComponent />} />
      </Switch>
    </Router>
  );
}

I want to load a different component on that route.

Version of react-router-dom is 5.2.0.

This code is not working, it appears a red line under <Route path... stating this:

Operator '<' cannot be applied to types 'number' and 'typeof Route'.ts(2365)
(alias) class Route<T extends {} = {}, Path extends string = string>
import Route

Any ideas?

LATER EDIT:

There is an answer stating that replacing that line with component={NextComponent} will get rid of the error message. That's true but is it possible to send props to that component in this case?

For example, for component={<NextComponent someProps={something} />} seems possible but not for component={NextComponent}

CodePudding user response:

In react-router-dom v5 you don't specify the component prop as a JSX literal (the RRDv6 syntax), just pass a reference to the component.

component={NextComponent} instead of component={<NextComponent />}

Code

export function MyComponent({ list }: MyComponentProps) {
  return (
    <Router>
      <Switch>
        <Route path={list[0].url} component={NextComponent} />
      </Switch>
    </Router>
  );
}

If you need to pass along additional props then you must use the render prop. This effectively renders an anonymous React component. Don't forgot you may need to also pass along the route props to the rendered components.

export function MyComponent({ list }: MyComponentProps) {
  return (
    <Router>
      <Switch>
        <Route
          path={list[0].url}
          render={props => <NextComponent {...props} something={value} />} 
        />
      </Switch>
    </Router>
  );
}

Route render methods

  • Related