'Hashrouter no slash with react-router-dom v6
I want to add a hash with no slash to my path, like: /#store/flowers/price
but since I'm not using react-router-dom v5 anymore, the v6 does not let me work with <HashRouter hashType='noslash'>
My code:
import React from 'react'
import { HashRouter, Routes, Route } from 'react-router-dom'
import FlowersPrice from './views/Store/Flowers/FlowersPrice'
return (
<>
<HashRouter>
<Routes>
<Route path={'/store/flowers/price'} element={<FlowersPrice />} />
</Routes>
</HashRouter>
</>
)
}
export default App
This will only be available at /#/store/flowers/price
and I want to still remove the slash /#/store
My react-router-dom version: "react-router-dom": "^6.2.2"
Solution 1:[1]
It appears this is no longer possible.
For those looking to just make their projects compatible with old URLs, you can force update any hash missing the leading "/". This is not the most elegant solution, but it solved it for me.
Add this to your index.js entry file:
const forceSlashAfterHash = () => {
let _hash = window.location.hash;
if (_hash[1] && _hash[1] != '/') {
window.location.href = window.location.origin + window.location.pathname + window.location.search + "#/" + _hash.slice(1);
}
}
forceSlashAfterHash();
window.addEventListener('hashchange', forceSlashAfterHash);
When the page loads or the hash changes, it checks for a leading "/" in the hash, and if not present, adds one.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Philip Stevens |