I have a React component that contains a <BrowserRouter/>
, but would like to be able to pass in any of react-router
's Router
s as a prop in order to test it easily. I've tried a few ways, but nothing I've tried makes typescript happy.
This first attempt won't work because I can't come up with a type annotation for Router
in the props that will work. I thought react-router-dom
s Router
type would work, but it doesn't.
export interface TestProps {
Router: React.ComponentClass | React.StatelessComponent;
// also tried: Router, BrowserRouter | MemoryRouter | etc.
}
export class TestComponent extends React.Component<TestProps, any> {
render() {
const { Router } = this.props;
return (
<Router>
// ...some routes here
</Router>
);
}
}
I made a stab at passing the router in as a JSX.Element as well, but that won't work either, since the TestComponent would need to set the props.children for that element.
Is the only way around this to make an HOC for each of the Router types?
EDIT: While almost certainly not the right way to do it, React.cloneElement()
will let me do what I want to for now.
export interface TestProps {
router: JSX.Element;
}
export class TestComponent extends React.Component<TestProps, any> {
render() {
const { router } = this.props;
const children: React.ReactNode = (
<div>
// ...some routes here
</div>
);
const Router = React.cloneElement(router, router.props, children);
return (
<div>
{Router}
</div>
);
}
}