Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
- ReactDOM.render(
- <Router>
- <App />
- </Router>,
- document.getElementById('root'),
- );
- import React, { Component } from 'react';
- import { Switch, Route } from 'react-router-dom';
- import { withRouter } from 'react-router'
- class App extends Component {
- state = { prevLocation: '' };
- // Use the context api to retrieve the value in your Link
- getChildContext = () => (
- {
- prevLocation: this.state.prevLocation,
- }
- );
- componentWillReceiveProps(nextProps) {
- if (nextProps.location !== this.props.location) {
- this.setState({ prevLocation: this.props.location.pathname });
- }
- }
- render() {
- return (
- <div>
- <Switch>
- // ...
- </Switch>
- </div>
- );
- }
- }
- App.childContextTypes = {
- prevLocation: PropTypes.string,
- };
- export default withRouter(App);
- import React from 'react';
- class GoBack extends React.Component {
- render() {
- return <Link to={this.context.prevLocation}>click</Link);
- }
- }
- GoBack.contextTypes = {
- prevLocation: PropTypes.string,
- };
Add Comment
Please, Sign In to add comment