Error: useRoutes() may be used only in the context of a <Router> component

Viewed 5788

I'm adding React modules dynamically using System JS, and it works great!
Except if I try to use the react-router context from the loaded module.

"react-router-dom": "6.0.0-beta.0"

You can see in the react component explorer that there is definitely a <Router> component as an ancestor.
The routing works fine in the host application - it only breaks when called from a dynamically loaded component.

I'm a novice with React, so I could be making a wrong assumption of how the contexts are provided to deeply nested or dynamically loaded children.

enter image description here

Router is mounted here -
https://github.com/savantly-net/sprout-platform/blob/47cb99f7076bf6df09d9fec8e2d6c7ee78ce08af/frontend/apps/webapp/src/index.tsx#L204

Module is being loaded here -
https://github.com/savantly-net/sprout-platform/blob/47cb99f7076bf6df09d9fec8e2d6c7ee78ce08af/frontend/apps/webapp/src/features/plugins/AppRootPage.tsx#L84

The module element that throws the exception is here -
https://github.com/savantly-net/sprout-platform/blob/47cb99f7076bf6df09d9fec8e2d6c7ee78ce08af/backend/modules/forms/src/plugin/FormsRootPage.tsx#L47

2 Answers

The problem was due to having the react-router-dom lib in the module bundle.
When the dynamic module loaded, it was using it's own version of the lib, rather then the one provided by the host application.

I added this to the externals in my webpack/rollup config, and the problem was solved.

I can now have children routes managed by a plugin inside a host application! =].

Webpack -
https://github.com/savantly-net/sprout-platform/blob/e746085ebd65820fd449c968385913f2cc86ee0d/frontend/tools/sprout-toolkit/src/config/webpack.plugin.config.ts#L176

Wrapping <App /> inside <Router> </Router> will resolve the issue.

import { BrowserRouter as Router } from "react-router-dom";

<Router>
 <App/>
</Router>
Related