How to access the history object in the new React Router v4

I tried all the suggested methods in other threads and it still does not work, so I am posting a question.

So, I have history.jssomething like this

import { createBrowserHistory } from 'history';

export default createBrowserHistory;

My index.js

render((
        <Router history={history}>
            <div>
                <Route component={App}/>
            </div>
        </Router>
    ), document.getElementById('root')
);

Home.js Looks like this

class Home extends Component {
    handleSubmit(e) {
        e.preventDefault();

        let teacherName = e.target.elements[0].value;
        let teacherTopic = e.target.elements[1].value;
        let path = `/featured/${teacherName}/${teacherTopic}`;
        history.push(path);

    }

    render() {
        return (
            <div className="main-content home">
                <hr />
                <h3>Featured Teachers</h3>
                <form onSubmit={this.handleSubmit}>
                    <input type="text" placeholder="Name"/>
                    <input type="text" placeholder="Topic"/>
                    <button type="submit"> Submit </button>
                </form>
            </div>
        );
    }
}

export default Home;

Home.js is actually routed in app.js, which is routed in index.js.

The problem is that I cannot access the history object anywhere.

The methods I tried are given below

1) this.context.history.push(path)in home.js - cannot access undefined context

2) this.props.history.push(path)in home.js - cannot access undefined details

3) browserHistory.push(path)in index.js - this is deprecated now

4) the path above is _history2.default.push is not a function

, , . , https://reacttraining.com/react-router/web/api/Route/Route-render-methods

, v2 v3 .

-, , React Router v4, ? .

+6
1

, withRouter.

...

import { withRouter } from 'react-router'

class Home extends Component {
  functionMethod() {
    const { history: { push } } = this.props;
    doStuff();
    push('/location');
  }
  ...
}

export default withRouter(Home);

https://reacttraining.com/react-router/web/api/withRouter

+10

Source: https://habr.com/ru/post/1016154/


All Articles