Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass params with history.push/Link/Redirect in react-router v4?

How can we pass parameter with this.props.history.push('/page') in React-Router v4?

.then(response => {        var r = this;         if (response.status >= 200 && response.status < 300) {              r.props.history.push('/template');           }); 
like image 739
IshanGarg Avatar asked May 22 '17 19:05

IshanGarg


People also ask

How do you pass additional data while redirecting to a route in react?

Using Link So when we click on the Register link, it will redirect to the /register route. But Link also allows us to pass additional data while redirecting. Here, at the place of data_you_need_to_pass , we can pass a string or object , array and so on and in the /register route we will get that data in props.


2 Answers

First of all, you need not do var r = this; as this in if statement refers to the context of the callback itself which since you are using arrow function refers to the React component context.

According to the docs:

history objects typically have the following properties and methods:

  • length - (number) The number of entries in the history stack
  • action - (string) The current action (PUSH, REPLACE, or POP)
  • location - (object) The current location. May have the following properties:

    • pathname - (string) The path of the URL
    • search - (string) The URL query string
    • hash - (string) The URL hash fragment
    • state - (string) location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history.
  • push(path, [state]) - (function) Pushes a new entry onto the history stack
  • replace(path, [state]) - (function) Replaces the current entry on the history stack
  • go(n) - (function) Moves the pointer in the history stack by n entries
  • goBack() - (function) Equivalent to go(-1)
  • goForward() - (function) Equivalent to go(1)
  • block(prompt) - (function) Prevents navigation

So while navigating you can pass props to the history object like

this.props.history.push({   pathname: '/template',   search: '?query=abc',   state: { detail: response.data } }) 

or similarly for the Link component or the Redirect component

<Link to={{       pathname: '/template',       search: '?query=abc',       state: { detail: response.data }     }}> My Link </Link> 

and then in the component which is rendered with /template route, you can access the props passed like

this.props.location.state.detail 

Also keep in mind that, when using history or location objects from props you need to connect the component with withRouter.

As per the Docs:

withRouter

You can get access to the history object’s properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will re-render its component every time the route changes with the same props as <Route> render props: { match, location, history }.

like image 148
Shubham Khatri Avatar answered Oct 13 '22 15:10

Shubham Khatri


Extending the solution (suggested by Shubham Khatri) for use with React hooks (16.8 onwards):

package.json (always worth updating to latest packages)  {      ...       "react": "^16.12.0",      "react-router-dom": "^5.1.2",       ... }  

Passing parameters with history push:

import { useHistory } from "react-router-dom";  const FirstPage = props => {     let history = useHistory();      const someEventHandler = event => {        history.push({            pathname: '/secondpage',            search: '?query=abc',            state: { detail: 'some_value' }        });     };  };  export default FirstPage;   

Accessing the passed parameter using useLocation from 'react-router-dom':

import { useEffect } from "react"; import { useLocation } from "react-router-dom";  const SecondPage = props => {     const location = useLocation();      useEffect(() => {        console.log(location.pathname); // result: '/secondpage'        console.log(location.search); // result: '?query=abc'        console.log(location.state.detail); // result: 'some_value'     }, [location]);  };  
like image 29
akhouri Avatar answered Oct 13 '22 16:10

akhouri