DEV Community

Paw
Paw

Posted on

Redirect all url with # from HashRouter to BrowserRouter

I changed HashRouter to BrowserRouter and now I would like to redirect all urls to remove # from them. (Url are in e.g. mailing - so I have to do it).

I found a similar topic to this, but none of the solutions there works for me.

import { BrowserRouter } from 'react-router-dom'

class Index extends Component {

    render() {

        return (
<BrowserRouter>
  <Switch>
    <Route exact path={"/"} component={() => <HomePage />}/>
    <Redirect from='/#/bus/:category' to '/bus/:category' />
    <Route exact path='/bus/:category' component={BusCategory} />
  </Switch>
</BrowserRouter>
        )
    }
}

ReactDOM.render(<Index />, document.getElementById("index"));

It's redirecting only to HomePage.

Next solution also not working:

import { BrowserRouter } from 'react-router-dom'

class Index extends Component {

    render() {


 const history = useHistory()

  if (location.hash.startsWith('#/')) {
    history.push(location.hash.replace('#', '')) // or history.replace
  }

        return (
<BrowserRouter>
  <Switch>
    <Route exact path={"/"} component={() => <HomePage />}/>
    <Route exact path='/bus/:category' component={BusCategory} />
  </Switch>
</BrowserRouter>
        )
    }
}

ReactDOM.render(<Index />, document.getElementById("index"));

and the last one also nothning :(

import { BrowserRouter } from 'react-router-dom'

class Index extends Component {

    render() {

        return (
<BrowserRouter>
  <Switch>
    <Route exact path={"/"} component={() => <HomePage />}/>
    <Route exact path='/bus/:category' component={BusCategory} />
    <Route path={"/bus/:category"} render={({ location }) => <Redirect strict to={location.hash.replace('#', '')} />} />

  </Switch>
</BrowserRouter>
        )
    }
}

ReactDOM.render(<Index />, document.getElementById("index"));

I've probably already tried all the options, if anyone can help me I'll be extremely grateful.

Top comments (1)

Collapse
 
praveennagaraj97 profile image
Praveen • Edited