Back button back to go back, like the browser back button when not on the home path

In the header, I have a menu button that when clicked will display different links for the transition. However, I would just like to show the menu button when it is on the home path (ie "/"). And when I go to other pages, I would like to change the menu button to the back button . This return button should resemble a browser button that will return one step at a time until I get back to my home path. How can i achieve this? I use "react": "^ 15.1.0" and "reaction-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> ); } } 
+7
javascript reactjs react-router
source share
2 answers

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 keeps track of the path and decides whether the show button or not.

And hashHistory.goBack() , works like a browser back button

enter image description here

+4
source share

You need to add the router to your context ( https://facebook.imtqy.com/react/docs/context.html ).

 Header.contextTypes = { router: React.PropTypes.object.isRequired }; 

A react router usually populates the this.context.router variable.

There are many available methods available with this this.context.router object, for example goBack () ( https://github.com/reactjs/react-router/blob/master/docs/API.md#goback ).

+2
source share

All Articles