简体   繁体   中英

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

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?

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>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM