0

I'm following a ReactJS tutorial that is using React Router 3 while I'm using React Router 4. At one point in the tutorial routing is done programatically Like this

import React from "react";
import { browserHistory } from "react-router";

export class User extends React.Component {
    onNavigateHome() {
        browserHistory.push("/home");
    }

    render() {
        return (
            <div>
                <h3>The User Page</h3>
                <p>User ID: {this.props.params.id}</p>
                <button onClick={this.onNavigateHome} className="btn btn-primary">Go Home!</button>
            </div>
        );
    }
}

I've done some research and it seems like in React Router 4 I have to make my own history.

I got this working with withRouter

import React from "react";
import { Route, Redirect, withRouter } from "react-router-dom";

export class User extends React.Component {

    onNavigateHome() {
        this.props.history.push("/home")
        {/*<Redirect push to="/home"/>*/}
    }

    render() {
        return (
            <div>
                <h3>The User Page</h3>
                <p>User ID: </p>
                <button onClick={() => this.onNavigateHome()} className="btn btn-primary">Go home!</button>
            </div>
        );
    }
}

export default withRouter(User);

But I'm not sure how I should use the history that I have created. What is the prefererad way to do this in React Router 4?

I also had a look at the alternative solution with Redirect. I wasn't able to get this one working. Any suggestions what I'm missing?

import React from "react";
import { Route, Redirect, withRouter } from "react-router-dom";

export class User extends React.Component {

    onNavigateHome() {
        <Redirect push to="/home"/>
    }

    render() {
        return (
            <div>
                <h3>The User Page</h3>
                <p>User ID: </p>
                <button onClick={this.onNavigateHome} className="btn btn-primary">Go home!</button>
            </div>
        );
    }
} 
g3blv
  • 3,877
  • 7
  • 38
  • 51
  • Possible duplicate of [How to navigate dynamically using react router dom](https://stackoverflow.com/questions/44137774/how-to-navigate-dynamically-using-react-router-dom) – Mayank Shukla Jun 26 '17 at 11:17
  • Possible duplicate of [Using browserHistory.push to change Route dynamically doesn't work with react-router v4](https://stackoverflow.com/questions/44718840/using-browserhistory-push-to-change-route-dynamically-doesnt-work-with-react-ro) – Shubham Khatri Jun 26 '17 at 11:18
  • Possible duplicate of [How to push to History in React Router v4?](https://stackoverflow.com/questions/42701129/how-to-push-to-history-in-react-router-v4) – Chris Jun 26 '17 at 11:51

0 Answers0