Question: Call a method on componentWillReceiveProps based on previous path url


Call a method on componentWillReceiveProps based on previous path url

Answers 1
Added at 2016-12-30 16:12

What I am trying to achieve is the call a method based on previous path url (I am using react-router).

Previous path URL looks like

and on successful sign in user is redirected to

Now, when my component is mounted and I see the new URL, I would like to trigger a method, but only if the user is signed in from the previous url that I specified in my question. The unique string in the previous URL is &join=true. How can I call a method in componentWillReceiveProps when the previous path contains &join=true

example pseudo code looks like

import React, { PropTypes, Component } from "react";
import MyComponentView from "./view";

class MyComponent extends Component {
    componentWillReceiveProps(nextProps) {
        if ( // prevoius path logic check ) {
            this.props.myMethod(); // Calling the method over here

    render() {
        return (
            <MyComponentView {...this.props} />

export default MyComponent;

Update: Adding the code with redirect functionality

_getCurrentPathName() {
        let path = window.location.pathname +;
        if (path === "/") {
            return undefined;
        return path;

transitionToSigninAndAutoJoin(query) {
    const q = Object.assign({}, query, {
        f: this.props.params.slug,
        nextPath: this._getCurrentPathName(),
        join: true

    this.transitionTo({ pathname: "/signin", query: q });

In summary, when I click a button in my component it checks whether the user is logged in or not. If the user is logged in I am calling the method myMethod() as mention in the original code sample.

If not, I am redirecting the user to sign-in page (calling transitionToSigninAndAutoJoin), which take the current path and and redirects to signin path. For e.g. if my current path name is and the user is not logged in, the new redirection url looks like

Upon sucessful signin user is redirected back to, but now I want to call myMethod() automatically when the component is mountedd. However, myMethod() should only be called automatically when the previous url contains &join=true

Answers to

Call a method on componentWillReceiveProps based on previous path url

nr: #1 dodano: 2016-12-30 18:12

Instead of relying on the previous URL, you can add a state object to the location descriptor when you are redirecting.

function redirectAfterSignin() {
  const {
    join = false
  } = this.props.location.query

    pathname: nextPath,
    state: { join }

Then in your other component, you will just need to check the location.state prop to determine the join value.

class MyComponent extends React.Component {
  componentWillReceiveProps(nextProps) {
    if (nextProps.location.state.join) {
      // do something
Source Show
◀ Wstecz