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>
);
}
}