I have some state values using in the App.js as below

constructor(){
  super()
  this.state = {
    text: "hello world"
  }
}

handleClick() {
    this.setState({text: "good morning})
}

render() {

    return (
        <BrowserRouter>
            <div>
                <Header />
                <Switch>
                    <Route exact path="/" component={() => <Home handleClick={this.handleClick()} {...this.state}/>} />
                    <Route path="/login" component={Login} {...this.state}/>
                    />
                </Switch>
            </div>
        </BrowserRouter>
    );
}

Inside my Home component I have a button click function and on clicking the handleClick function will trigger and the state value will change. I want to retain the new state value and pass it to login component as well as Home component after the login process is completed.

Right now when I goes to /login and go back to / the default state value is getting inside the Home component.

The state value is changing to new value on onClick function and there is no issue with that. I have the binding methods added in the App.js for the functions.

How can I retain the new state value to use inside Home component after some other router is called?

2 Answers

0
gergana On

Setting state in handleClick should be:

handleClick() {
  this.setState({text: "good morning"})
}
0
Ricardo Lopes On

You need to either bind the function in the constructor, or use arrow functions instead. Additionally, you need to pass the function's reference only, without calling it. That means you can't use the () when passing it as a prop. And one last thing, you were passing the destructured state to the Route component instead of the Login component.

constructor(){
  super()
  this.state = {
    text: "hello world"
  }

  // binding in constructor not needed if using arrow function
  this.handleClick = this.handleClick.bind(this);
}

// arrow function not needed if binding in constructor
handleClick = () => {
    this.setState({text: "good morning})
}

render() {

    return (
        <BrowserRouter>
            <div>
                <Header />
                <Switch>
                    <Route
                      exact
                      path="/"
                      component={() => (
                        <Home 
                          // important: this.handleClick without ()
                          handleClick={this.handleClick}
                          {...this.state}
                        />
                      )}
                    />
                    <Route
                      path="/login"
                      component={() => (
                        <Login {...this.state} />
                      )}
                    />
                </Switch>
            </div>
        </BrowserRouter>
    );
}