user12990369
user12990369

Reputation:

this.props.function is not a function

Im new to React and having trouble setting parent state from child.

Parent Component: Router.js

class Router extends Component{
    constructor(props){
        super(props);
        this.handler = this.handler.bind(this);
        this.state = {
            login: true,
        }
    }
    handler() {
        console.log("hi");
        this.setState({
            login: true,
        });
    }

    render(){
        return(
            <div>
                <BrowserRouter>
                <Route exact path="/" component={ Register }></Route>
...other routes
                    <Route path="/login" handler={this.handler} component={ Login } />
            </div>
        );
    }
}

export default Router;

Child Component Login.js

class Login extends Component {
...some code to get back end node js data
if(got node data){
      this.props.handler();
     this.props.history.push('/home');
}
 render (){
        return (
<div>
<button className="button" onClick = {this.checkUser.bind(this)}>
                            Login
                        </button>
<div>
)
}

I keep getting "this.props.handler is not a function"

Did i format my handler wrong? I am a bit confused.

Thank

Upvotes: 0

Views: 281

Answers (1)

dance2die
dance2die

Reputation: 36895

You are passing this.handler to the Route component not to Login, when you do

<Route path="/login" handler={this.handler} component={ Login } />

You have two choices to pass this.handler to Login component.

You can either pass props via render

<Route path="/login" render={ () => <Login handler={this.handler} />} />

or nest it

<Route path="/login">
  <Login handler={this.handler} />
</Route>

Upvotes: 2

Related Questions