Search code examples
javascriptreactjsreact-routerbrowser-history

Obtaining pathname of current route in React Router w/browserHistory


there seems to be some disagreement between various sources on what the most efficient way of obtaining the pathname of the current url using React Router is (using browserHistory). Below is a snippet of my Provider and routes:

ReactDOM.render(
        <Provider store={Store}>
            <Router history={browserHistory}>
                <Route path="/tools/customer-lookup" component={CustomerLookupApp} />
                <Route path="/tools/customer-lookup/profile/:id" component={CustomerLookupProfileWrapper} />
                <Route path="/tools/customer-lookup/profile/:id/store/:storeid" component={CustomerLookupStoreProfileWrapper} />
                <Route path="/tools/customer-lookup/profile/:id/store/:storeid/transaction/:transid" component={CustomerLookupStoreItemsWrapper} />
            </Router>
        </Provider>,
        document.getElementById('customer-lookup-main'));
}); 

Tried logging this.props.location.pathname in various components but always comes up undefined. Same thing with this.context.

Any advice is appreciated, thanks.


Solution

  • The property this.props.location.pathname will not be available in "various" components, it will only be available in your route handing components. i.e. CustomerLookupApp, CustomerLookupProfileWrapper, CustomerLookupStoreProfileWrapper, CustomerLookupStoreItemsWrapper.

    If you need the pathname further down the tree then you can pass it down as props.