Home > Blockchain >  Migration to react-router-dom v6
Migration to react-router-dom v6

Time:02-12

I've had a problem with migration between react-router-dom v5 to v6. After update my package I do a few upgrades in the code. Below is my version of code in v5 and with v6 and also Routing component which give me a problem.

v5

export default function App() {
  return (
    <div className="App">
      <Switch>
        <AppContextProvider>
          <Routing />
        </AppContextProvider>
      </Switch>
    </div>
  );
}

v6

export default function App() {
  return (
    <div className="App">
      <AppContextProvider>
        <Routes>
          <Routing />
        </Routes>
      </AppContextProvider>
    </div>
  );
}

<Routing /> component

const Routing = (): JSX.Element => {
  return (
    <>
      {publicRouting.map(({ path, component }, i) => (
        <Route key={i} path={path} element={component} />
      ))}
      {isAuthenticated() && (
        <Main>
          {routing.map(({ path, component }, i) => (
            <Route  key={i} path={path} element={component} />
          ))}
        </Main>
      )}
    </>
  );
};

Right now console throw me this error:

index.tsx:19 Uncaught Error: [Routing] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

can someone tell me how to solve this problem? It looks like this component has incompatible type and cannot go as children between Routes component, but why they changed it? How to correct my Routing component?

Thanks for any help!

CodePudding user response:

In react-router-dom v6 the Routes component can have only Route or React.Fragment as a valid child, and the Route component can only have Routes or another Route component as parent.

The Routes component effectively replaced the RRDv5 Switch component in that it handles the route matching and rendering logic, and is now required to directly wrap the Route components it's managing.

Move the Routes component into Routing to wrap directly the Route components being mapped.

export default function App() {
  return (
    <div className="App">
      <AppContextProvider>
        <Routing />
      </AppContextProvider>
    </div>
  );
}

...

const Routing = (): JSX.Element => {
  return (
    <>
      <Routes>
        {publicRouting.map(({ path, component }, i) => (
          <Route key={i} path={path} element={component} />
        ))}
      </Routes>
      {isAuthenticated() && (
        <Main>
          <Routes>
            {routing.map(({ path, component }, i) => (
              <Route  key={i} path={path} element={component} />
            ))}
          </Routes>
        </Main>
      )}
    </>
  );
};
  • Related