I was reading react-router-redux examples and I confused, what is the difference beetween:
import { Redirect } from 'react-router-dom' ... <Redirect to='/login' />
and
import { push } from 'react-router-redux' ... push('/login')
Use the history. push and history. replace in a component (usually wrapped with the withRouter HOC, so that you can have access to the location object without having to pass it from parent to child. Use the <Redirect> component with or without the push property, depending.
To redirect to another page on button click in React: Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Call the navigate() function, passing it the path - navigate('/about') .
With the release of React Router v6, the Redirect component was removed and replaced with the Navigate component, which operates just as the Redirect component does by taking in the to prop to enable you redirect to the page you specify.
The history. push() function belongs to react-router-dom and used to move from the current page to another one. It takes the first argument as a destination path and a second argument as the state. Note: You can only use this.
Redirect
Rendering a <Redirect>
will navigate to a new location. The new location will override the current location in the history stack,
like server-side redirects (HTTP 3xx) do.
whereas History
push function Pushes a new entry onto the history stack
The <Redirect>
component will, by default, replace the current location with a new location in the history stack, basically working as a server-side redirect.
But it can also be used with the property push
and in this case it will push a new entry into the history stack, working the same way as history.push
.
In fact the <Redirect>
component uses the history push
and replace
methods behinds the scene. It is just a more React way of navigating.
So basically you have two ways of navigating:
Use the history.push
and history.replace
in a component (usually wrapped with the withRouter
HOC, so that you can have access to the location
object without having to pass it from parent to child.
Use the <Redirect>
component with or without the push
property, depending
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With