Anna Lee
Anna Lee

Reputation: 951

How to pass props(method) with Redirect component

I know how to pass state to redirect component like below.

<Redirect
    to={{
      pathname: "/login",
      state: { isLoggedIn: this.state.isLoggedIn }
    }}
 />

However, I can't find well the way how to pass method to redirect component. What I want is to pass a method (handleLogin) to redirect component like below. Could you please give some help?

<Redirect
    to={{
        pathname: "/login",
        state: { handleLogin: this.handleLogin }
     }}
 />

Upvotes: 3

Views: 2012

Answers (2)

Te Hoa Huynh
Te Hoa Huynh

Reputation: 21

I just came across a similar problem.

In my case, I need to pass a function to the component through <Redirect />, so what I did was to create another property to pass the function. (Sorry if I used the wrong terminologies, just started coding for 2 months).

In your case, this is what I would try.

<Redirect
  to={{
    pathname: "/login",
    handleLogin: this.handleLogin,
    state: { isLoggedIn: this.state.isLoggedIn }
  }}
/>

Upvotes: 2

TLadd
TLadd

Reputation: 6884

You cannot pass a function in the state property of the to prop of Redirect. Only serializable data is allowed. This follows the behavior of the native history api, which is utilized by the history package, which react-router utilizes. See this issue for more details. Also notice in that comments that is oftentimes not advised to use state

While it is tempting to pass state through location.state, I would caution against using it for anything but ephemeral data. When you navigate directly to a page, location.state is always null, so you would have to have built-in safe-guards to handle this.

In order to handle different behaviors in your login form based on where they are being redirect from, I would probably pass some serializable data in the query string and then use that data to decide what to do in the component rendered at /login. So something like this:

// Redirect
<Redirect to={`/login?param1=a`} />

// Login component
import qs from "qs";

class Login extends React.Component {
  login = () => {
    const { param1 } = qs(this.props.location.search);
    if (param1 === "a") {
      // Do something
    } else {
      // Do something else
    }
  }

  render() {
    <button onClick={this.login} type="button">Login</button> 
  }
}

Upvotes: 1

Related Questions