Home > Software engineering >  Component not changing state in React
Component not changing state in React

Time:10-29

In my app I'm trying to change the state of route when I click submit in my SignIn component. I want to pass onRouteChange as props. Is the function not being passed to the other component?

App:

class App extends Component {
  constructor() {
    super();
    this.state = { route: "signed-out" };
  }
  onRouteChange = () => {
    this.setState({ route: "home" });
  };
  render() {
    return (
      <div class='main'>
        {this.state.route === "signed-out" ? (
          <div>
            <SignIn onRouteChange={this.onRouteChange}/>
          </div>
        ) : (
          <div>
            <SignOut  />
          </div>
        )}
      </div>
    );
  }
}

    

SignIn Component:

    const SignIn = ({ onRouteChange }) => {
      return (
        <div>
          <form>
            <div>Sign In</div>
            <div>Email</div>
            <input type='email' />
            <div>Password</div>
            <input type='password' />
            <input onClick={onRouteChange} type='submit' />
          </form>
        </div>
      );
    };

CodePudding user response:

You are passing the function to SignOut component but trying to use it in SignIn component.

Your App.js file should have this instead:

...
<div>
    <SignIn onRouteChange={this.onRouteChange} />
</div>
) : (
<div>
    <SignOut />
</div>
...

CodePudding user response:

I'd do this, I'd bind the onRouteChange to this in the constructor and redefine the onRouteChange as such:

class App extends Component {
  constructor() {
    super();
    this.state = { route: "signed-out" };
    this.onRouteChange = this.onRouteChange.bind(this); // new
  }

  onRouteChange() {
    this.setState({ route: "home" });
  };

  // rest of your code

Now with that function binded to this your code here <SignIn onRouteChange={this.onRouteChange}/> should now work.

  • Related