Reputation: 38682
I am developing a web browser extension that renders various links. These links may be rendered either inside an "application" path (app.html
in the extension), or from the browser action window (the extension button in the menu bar).
The application has a React router defined; the popup does not.
When I render the link in the application itself, I can use:
import { Link } from 'react-router-dom';
// ...
<Link to={...}>Foo</Link>
However, in the popup itself, this does not work, as I get the error:
Invariant failed: You should not use <Link> outside a <Router>
This makes sense of course. But I would like to create links via a helper function or component, and how can I determine whether I am currently "inside" a router?
Note that I could in principle pass down a prop that tells the component explicitly whether it is part of a router or not, but that seems very verbose.
Upvotes: 1
Views: 60
Reputation: 281726
You can determine if you have a Router component in the hierarchy by trying to obtain the history object using useHistory
hook
import { useHistory } from 'react-router-dom';
const Comp = () => {
const history = useHistory();
if(!history) {
// no router in hierarchy
}
}
Upvotes: 2