74

How should you pass props with the Redirect component without having them exposed in the url?

Like this <Redirect to="/order?id=123 />"? I'm using react-router-dom.

6 Answers 6

117

You can pass data with Redirect like this:

<Redirect to={{
            pathname: '/order',
            state: { id: '123' }
        }}
/>

and this is how you can access it:

this.props.location.state.id

The API docs explain how to pass state and other variables in Redirect / History prop.

Source: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md#to-object

24
  • 1
    @SakhiMansoor Yes the object should contain pathname, search, state, etc which are values used by the browser history. Any custom values should be included in the state object which is one level down. It's cleaner and separates what's used by the browser history from your own custom object.
    – Anas
    Aug 28, 2018 at 18:53
  • 2
    Thank you @Anas and SakhiMansoor for the help. You guys both deserve the solution mark ! :)
    – Michiel
    Aug 28, 2018 at 18:56
  • 1
    @SakhiMansoor I tried the same code but it gives me this error: Object literal may only specify known properties, and 'id' does not exist in type 'LocationDescriptor<any>'. Oct 27, 2018 at 14:51
  • 1
    This works apparently <Redirect to={{ pathname: "/app/AntennaAdd", state: {id: "123"} }} />; Oct 27, 2018 at 14:55
  • 3
    Hi... I am having a bit trouble receiving the state param passed with redirect. this.props.location gives me undefined. Any suggestions? Jan 3, 2019 at 13:37
61

You should first pass the props in Route where you have define in your App.js

<Route path="/test/new" render={(props) => <NewTestComp {...props}/>}/>

then in your first Component

<Redirect
            to={{
            pathname: "/test/new",
            state: { property_id: property_id }
          }}
        />

and then in your Redirected NewTestComp you can use it where ever you want like this

componentDidMount(props){
console.log("property_id",this.props.location.state.property_id);}
7
  • 4
    Underrated answer- this is a full solution; simply adding the line in the above answers doesn't properly pass the props. May 29, 2020 at 20:22
  • This is the CRUCIAL part. Simple and very helpful to say the least!
    – sonic98
    Aug 20, 2020 at 10:59
  • 1
    Flagged as new correct answer since this one has more information.
    – Michiel
    Aug 27, 2020 at 7:00
  • can you elaborate on 'then in your first Component'? I'm having trouble fitting this all together. which component is the 'first component'?
    – sammms
    Apr 27, 2021 at 15:17
  • 1
    @sammms not the author, but I believe they just meant in the Redirect Component. You can add this to any Redirect Component that you wish to pass props with, provided the Route component has a render prop set as a function. See here for more about Redirect to, and here for more about Route render
    – Mxt
    Jun 12, 2021 at 19:20
18

You can use browser history state like this:

<Redirect to={{
    pathname: '/order',
    state: { id: '123' }
}} />

Then you can access it via this.props.location.state.id

Source: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md#to-object

4
  • 4
    this.props.location gives me undefined. Any suggestions? Jan 3, 2019 at 13:39
  • 1
    @DhruvSinghal It means your component does not have access to the router props. Maybe try wrapping your component with withRouter
    – Anas
    Jan 3, 2019 at 14:46
  • 1
    @SagarKodte Same, mine was first :)
    – Anas
    Feb 21, 2019 at 15:07
  • I am getting this error Expected an assignment or function call and instead saw an expression . Any suggestions? Jul 29, 2019 at 8:17
5

With Functional Components/Hooks, react-router-dom version 5.2.0 and passing down both Function and regular props:

Using @Barat Kumar answer, here you can also see how to pass and access functions as props with Redirect. Note that there is also a difference in how you access the property_id prop.

The Route is the same:

<Route path="/test/new" render={(props) => <NewTestComp {...props}/>}/>

The Redirect:

<Redirect
  to={{
    pathname: "/test/new",
    testFunc: testFunc,
    state: { property_id: property_id }
  }}
/>

Accessing both props inside NewTestComp:

 useEffect(() => {
   console.log(props.history.location.testFunc);
   console.log(props.history.location.state.property_id);          
 }, []);

Note that "state" came from the use in Class Components. Here you can use any name you want and also pass regular props just like we did the function. So, departing a bit more from @Barat Kumar accepted answer, you can:

<Redirect
  to={{
    pathname: "/test/new",
    testFunc: testFunc,
    propetries: { property_id: property_id1, property_id2: property_id2},
    another_prop: "another_prop"
  }}
/>

And access those like so:

console.log(props.history.location.testFunc);
console.log(props.history.location.propetries.property_id1);
console.log(props.history.location.propetries.property_id2);
console.log(props.history.location.another_prop);
1
<Redirect to={{
    pathname: '/path',
    state: { id: '123' }
}} />

Then you can access it via this.props.location.state.id in the desired component

1
  • You can come with your own hook for the same purpose :
import { createBrowserHistory } from "history";

const withRefresh = createBrowserHistory({ forceRefresh: true });
const ROOT_PATH = process.env.PUBLIC_URL || "/myapp";

const useRedirectToLocation = (params="1") => {
if(params){
withRefresh.push({
    pathname: `${ROOT_PATH}/create`,
    state: { id: `${params}` }
  });
}
} 

export default  useRedirectToLocation;

  • and use it like :

 import useRedirectToLocation from  './useRedirectToLocation


const handleOnClick = params => useRedirectToAccounting(params)

const RedirectorComponent = () => <a onClick={handleOnClick}>{"Label"}</a>

** this can be further refactored based on requirement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.