score:1

Accepted answer

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! :)

score:0

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


Related Query

More Query from same tag