I am new to React Router and learn that there are so many ways to redirect a page:
Using browserHistory.push("/path")
import { browserHistory } from 'react-router';
//do something...
browserHistory.push("/path");
Using this.context.router.push("/path")
class Foo extends React.Component {
constructor(props, context) {
super(props, context);
//do something...
}
redirect() {
this.context.router.push("/path")
}
}
Foo.contextTypes = {
router: React.PropTypes.object
}
In React Router v4, there's this.context.history.push("/path")
and this.props.history.push("/path")
. Details: How to push to History in React Router v4?
I'm so confused by all these options, is there a best way to redirect a page?
This question is related to
reactjs
redux
react-router
You can also use react router dom library useHistory;
`
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
`
You also can Redirect
within the Route
as follows. This is for handle invalid routes.
<Route path='*' render={() =>
(
<Redirect to="/error"/>
)
}/>
Now with react-router v15.1
and onwards we can useHistory
hook, This is super simple and clear way. Here is a simple example from the source blog.
import { useHistory } from "react-router-dom";
function BackButton({ children }) {
let history = useHistory()
return (
<button type="button" onClick={() => history.goBack()}>
{children}
</button>
)
}
You can use this within any functional component and custom hooks. And yes this will not work with class components same as any other hook.
Learn more about this here https://reacttraining.com/blog/react-router-v5-1/#usehistory
One of the simplest way: use Link as follows:
import { Link } from 'react-router-dom';
<Link to={`your-path`} activeClassName="current">{your-link-name}</Link>
If we want to cover the whole div section as link:
<div>
<Card as={Link} to={'path-name'}>
....
card content here
....
</Card>
</div>
Source: Stackoverflow.com