In the header, I have a menu button, that when clicked will display different links to go to. However, I would only like to show the menu button when its in the home path (i.e., "/"). And when I navigate to other pages, I would like to change the the menu button to back button. This back button should be like the browser back button which will go back one step at a time, till I get back to the home path. How can I achieve this? I am using "react": "^15.1.0" and "react-router": "^2.5.2".
AppClient.js
ReactDom.render((
<Router history={hashHistory} >
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="home" component={Home}/>
...
...
<Route path="profile" component={Profile}>
<IndexRoute component={Timeline} />
<Route path="timeline" component={Timeline}/>
</Route>
<Route path="login" component={Login}/>
</Router>
), reactContainer)
App.js
export default class App extends React.Component {
render() {
const _this = this;
return (
<div>
<Header/>
...
...
</div>
);
}
}
Header.js
export default class Header extends React.Component {
render() {
return(
<header>
<div id="header-wrapper">
<div id="nav-bar-btn" class="nav">
// change Menu when its not home path that is "/"
<Menu>
// to Back
<Back>
</div>
</div>
</header>
);
}
}
A back button in the browser lets you back-up to the copies of pages you visited previously. The web browser's back and next buttons work well with web sites that provide information that changes infrequently, such as news and shopping web sites.
jsfiddle demo
import { hashHistory } from 'react-router';
export default class Header extends React.Component {
constructor(props){
super(props);
this.state={showBack:location.hash.split('?')[0]!=="#/"};
this.hook = hashHistory.listenBefore(loc=>
this.setState({showBack:loc.pathname!=="/"})
);
}
componentWillUnmount(){
this.hook(); //unlisten
}
render() {
return(
<header>
<div id="header-wrapper">
<div id="nav-bar-btn" class="nav">
{this.state.showBack?
<div onClick={()=>hashHistory.goBack()}>Go BACK</div>
: <Menu/>
}
</div>
</div>
</header>
);
}
}
listenBefore
watches path, and decides whether show button or not.
And hashHistory.goBack()
, works like browser back button
You need to add the router to your context (https://facebook.github.io/react/docs/context.html).
Header.contextTypes = {
router: React.PropTypes.object.isRequired
};
react-router will normally populate the this.context.router variable.
With this this.context.router object, there's a lot of methods available, like goBack() (https://github.com/reactjs/react-router/blob/master/docs/API.md#goback).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With