bluebrooklynbrim
bluebrooklynbrim

Reputation: 277

Get page location with React Router 4 and Hash routing

I want to get the location of the page I'm on in order to set up conditional rendering. Originally, I had something set up like this

const currentPath = window.location.pathname;
...
<h1>{currentPath}</h1>

And that would echo out the path as http://example.com/page.

But since I've switched to using HashRouter, and page links are generated like http://example.com/#/page, the only thing that echoes out is "/"

How do I get the location of the page after the hash?

Upvotes: 1

Views: 7099

Answers (2)

Shishir
Shishir

Reputation: 2546

Route in React-router v4 passes three props to the component it renders. One of these is the match object. It contains information about how the current path was matched.

In your case, you can use match.path or match.url to get the location of the page.

Something like this:

import React from 'react';
import { render } from 'react-dom';
import { Route, HashRouter as Router, Switch } from 'react-router-dom';

const Child = ({ match }) => {
  return <p>{match.url}</p>;
};

const App = () => (
  <Router>
    <Switch>
      <Route exact path='/' component={Child} />
      <Route exact path='/test1' component={Child} />
      <Route exact path='/test2' component={Child} />
    </Switch>
  </Router>
);

render(<App />, document.getElementById('root'));

Working code is available here: https://codesandbox.io/s/3xj75z41z1

Change the route in the preview section on the right to / or /test1 or /test2, and you'll see the same path displayed on the page.

Hope this helps. Cheers! :)

Upvotes: 1

Agney
Agney

Reputation: 19204

React Router provides location parameter out of box.

You can access it like location.pathname

For eg: if the component is Page:

const {HashRouter, Route, Link} = ReactRouterDOM;
function Page({location}) {
  return <p>{location.pathname}</p>;
}

class App extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <HashRouter>
        <div>
          <Route path="/page" component={Page} />
          <Link to='/page'>Link to Page</Link>
        </div>
      </HashRouter>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://unpkg.com/react-router-dom/umd/react-router.min.js"></script>
<script src="https://unpkg.com/react-router-dom/umd/react-router-dom.min.js"></script>
<div id="root"></div>

https://reacttraining.com/react-router/web/api/location

Upvotes: 0

Related Questions