Reputation: 235
We have a scenario where users link to our app from an external source and the url has a hash that does not play nice.
Example of the problematic URL : https://somewebsite.net/#/response/
That URL loads the component at this route: /
, but we want to load this one: /response
In order to fix that we used HashRouter
like this:
<Switch>
<Route exact path={['/', '/index.html']}>
{location.hash.includes('response') ? (
<HashRouter basename="/response" hashType="slash">
<Response/>
</HashRouter>
) : (
<Checkout />
)}
</Route>
<Route path="/order-received">
<OrderReceived />
</Route>
<Route path="/response">
<Response />
</Route>
</Switch>
That makes it so we can load the component, but it becomes a problem when we try to route to another path.
This does not work: history.push('/order-received');
Instead of going to https://somewebsite.net/order-received
is goes to https://somewebsite.net/#/response.order-received
I was able to overcome the problem by having this component load first to remove the /#
form the URL, but this feels really hacky.
const RemoveHashFromUrl = () => {
// removes `/#` from the URL and loads the component at https://somewebsite.net/response/
const url = window.location.href.replace('/#', '');
window.location.href = url;
return null;
};
export default RemoveHashFromUrl;
Is there a better way to do this?
Note: the <Switch>
is a child of <Router>
Upvotes: 3
Views: 1709
Reputation: 235
After reaching out for help on twitter, I got this answer and refactored to this:
const RemoveHashFromUrl = () => {
const url = window.location.href.replace('/#', '');
window.location.href = url;
};
<Switch>
<Route exact path={['/', '/index.html']}>
{location.hash ? removeHashFromUrl() : <Checkout />}
</Route>
<Route path="/order-received">
<OrderReceived />
</Route>
<Route path="/response">
<Response />
</Route>
</Switch>
Upvotes: 1