Reputation: 405
I am using react-router-dom hook useLocation() in third party component.
This component behavior depends on the current route by default but can be used also in app without react-router (user of the component shouldn't care about it)
The problem is that when the component is used outside of react-router scope it throws an error:
Cannot read property 'location' of undefined
My question is how to know if I can use useLocation() hook (how to know if a component is in react-router context)?
Upvotes: 0
Views: 832
Reputation: 405
The simplest solution from a similar question suggested by @Krzysztof Cieslinski is wrapping useLocation()
hook in try/catch block:
let path = ''
try {
path = useLocation().pathname
} catch (e) {}
Upvotes: 1