Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-router Redirect vs history.push

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') 
like image 372
tandav Avatar asked Feb 05 '18 09:02

tandav


People also ask

Should I use history push or redirect?

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.

What is the best way to redirect a page using react router?

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') .

What can I use instead of redirect in react?

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.

What is history PUSH IN react router?

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.


2 Answers

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

like image 101
Revansiddh Avatar answered Sep 22 '22 21:09

Revansiddh


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:

  1. 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.

  2. Use the <Redirect> component with or without the push property, depending

like image 35
Marcos Abreu Avatar answered Sep 23 '22 21:09

Marcos Abreu