Is it possible to match the # part of a route in React Router 4
if you actually want to match and get the parameters, use matchPath
.
import { useLocation, matchPath } from 'react-router-dom';
// your route you want to see if it matches
const routePath = '/overtherainbow/:country/#/city/:city/detail'
// somewhere while rendering
const location = useLocation();
useEffect(() => {
const matched = matchPath(location.pathname + location.hash, routePath);
if (matched){
// matched, do something with it, like setting state, fetching data or what not
console.log(matched.params); // will be {country:..., city:...}
}
}, [location])
@azium answer works fine as long as you don't need to use render or children prop in HashRoute. In which case this solution will work better :
import React from 'react';
import { Route } from 'react-router-dom';
const HashRoute = ({ hash, ...routeProps }) => (
<Route
render={({ location }) => (
(location.hash === hash) && <Route {...routeProps} />
)}
/>
);
export default HashRoute;
Use it like that :
<HashRoute hash="#modalB" component={ModalB} />
Or combine it with route matching :
<HashRoute hash="#modalB" path="/subPageOnly" component={ModalB} />
Not out of the box, but the beauty of React Router 4 is that it's incredibly easy to implement this yourself.
let HashRoute = ({ component: Component, path, ...routeProps }) => (
<Route
{...routeProps}
component={({ location, ...props }) =>
location.hash === path && <Component {...props} />
}
/>
)
<HashRoute path="#modalB" component={ModalB} />