score:7

Accepted answer

You can obtain the current pathname from the location prop of your route component.

Access location from this.props.location of your Route component. If you'd like to get it deeper in the tree, you can use whatever conventions your app has for getting props from high down low. One option is to provide it on context yourself:

// v2.0.x const RouteComponent = React.createClass({
childContextTypes: { location: React.PropTypes.object },

getChildContext() { return { location: this.props.location } } })

Have a look here.

To get the current path, you can just use location.pathname.

score:6

One way to access path is via this.props.location from a react component.

import React from 'react'
import { render } from 'react-dom'
import { browserHistory, Router, Route, Link } from 'react-router'

class Child extends React.Component {
  render() {
    let location = this.props.location
    return (
      <div>
        <h1>Child Component</h1>
        <p>{location.pathname}</p>
      </div>
    )
  }
}

class App extends React.Component {
  render() {
    return (
      <div>
            {this.props.children}
      </div>
    )
  }
}

render((
  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <Route path="child" component={Child} />
    </Route>
  </Router>
), document.getElementById('example'))

Another way if you want listen to changes in current location via history -

import { createHistory } from 'history'

let history = createHistory()

// Listen for changes to the current location. The
// listener is called once immediately.
let unlisten = history.listen(function (location) {
  console.log(location.pathname)
})

// When you're finished, stop the listener.
unlisten()

Related Query

More Query from same tag