I have a main component, App that holds all my Match components. I'd like to be able to display the current page at the top (in header, for example) but I'm having trouble getting the current pathname.
In App I have:
App.contextTypes = {
history: React.PropTypes.object,
};
And I pass the current path name to a component:
<Header currentPathname={this.context.history.location.pathname} />
However, App doesn't seem to update when the location changes. How can I listen for this and pass as a prop?
Presumably you want your header to show on all routes, if you're putting it above your Match components. In that case, also use Match for your header, and match on every pattern and you will have access to location through props.
<Match
pattern="/"
component={props => <Header pathname={props.location.pathname} />}
/>
Match is not a component anymore in react-router-dom (^4.3.1). Instead, I did this:
<Route path="" component={(props) => <Header {...props} page={"Main Page"} />}/>
In Header.js:
const Header = (props) => (
<header className="App-header">
{ console.log(props) }
<img src={logo} className="App-logo" alt="logo"/>
<TitleDiv>App Name : {props.page}</TitleDiv>
</header>
);
The result is App Name : Main Page