Ad

How Can I Pass Props From The Current Component To Another Component When The Second Component Is Called By Url?

We can send data as props from parent component to child component easily but what to do in case of no relationship between two components ?

Please Read my context first so that I can make you understand my problem easily.

In my e commerce react App, when any new user visits my site I want to recommend the user to register. In registration process I keep two steps.

  1. At first I want to take his mobile number from only one input field. when he fills the field and press 'continue' button -
  2. I want to take him another page (component) where from I can take his name, password etc.

Here these two components are independent to each other. When user hits the 'continue' button I am calling a and redirect him to another component.

Now my question is How do I preserve this mobile number in 1st component and send to the 2nd component

[N.B: I don't want the mobile number be visible in the url when calling the 2nd Route]

First Component

export default class FirstComponent extends Component {
    render() {        
        return (
            <div>                
                <input type="text" placeholder="Type Mobile number" />
                <Link to={{ pathname: '/signup' }}>
                    <button>Continue</button>
                </Link>
            </div>
        )
    }
}

Second Component

export default class SecondComponent extends Component {
    render() {        
        return (
            <div>       
                <input type="text" placeholder="Type Mobile number" />

            </div>
        )
    }
}

Router

<Route exact path="/signup" render={(props) => {return <SecondComponent />} }/>
Ad

Answer

You can do it this way:

<Link to={{ pathname: '/signup', state: { number: 3199192910} }}>
                    <button>Continue</button>
                </Link>

And you can access that in your signup component like:

import {withRouter} from 'react-router';

 class SecondComponent extends Component {
    render() { 
      // get the number 
      console.log(this.props.location.state.number)

        return (
            <div>       
                <input type="text" placeholder="Type Mobile number" />

            </div>
        )
    }
}

export default withRouter(SecondComponent);

Check out this example, Quotes is what you should be looking at:

Edit reverent-swartz-044s2

Ad
source: stackoverflow.com
Ad