0

I'm currently writing a small web-app in react and since it's my first time effectively using javascript i'm encountering some weird problems. I have a class A that should forward some behavior to its child components, but for whatever reason the child components methods can't be found an i receive the is not a function error.

Here the code:

A.jsx:

class A extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            type:""
        };
        this.foo = this.foo.bind(this);
        this.b = <B onClick={() => this.setState({type: "b"})}/>;
        this.c = <C onClick={() => this.setState({type: "c"})}/>;
    }

    render(){
        return (
        <SomeExternalStuff 
            sendRequest={this.foo}
            //some props...>
            {this.b}
            {this.c}
        </SomeExternalStuff>
        );
    }

    foo( test ){
        console.log(this.deletionButton);

        switch(this.state.type){
            case "b":
                this.b.bar(test);
                break;
            case "c":
                this.c.bar(test);
                break;
        }
    }
}

B.jsx:

class B extends React.Component{
    static TITLE = "<some title>";

    render(){
        return (
            <Button type="submit" variant="danger" onClick={this.props.onClick}>
                {B.TITLE}
            </Button>
        );
    }

    bar(test){
        console.log("I'M IN B");
    }
}

C.jsx is nearly the same as B.jsx. I get the same error for both components.

Sali Ke
  • 11
  • 1
  • 4
  • It is because the name of the prop was `sendRequest` as ```sendRequest={this.sendRequest}``` ,but you are using `onClick` in B component, which is not defined in the parent component – Rajat Verma Apr 19 '20 at 13:42
  • I would recommend you not to name another variable or function on the name of a prop.This will only increase confusion in your components. – Rajat Verma Apr 19 '20 at 13:45
  • I changed my question, and as far as i understood your reply this should solve the problem, but unfortunately it doesn't :/ – Sali Ke Apr 19 '20 at 14:00
  • just as a side note https://reactjs.org/docs/state-and-lifecycle.html#using-state-correctly – Person Apr 19 '20 at 14:09
  • Change `onClick` prop usage (which its predefeined js method) to `handleClick` or something like that – Hagai Harari Apr 19 '20 at 14:22
  • I don't get where have you defined the `onClick` prop? That must be `this,props.sendRequest` instead of `this.props.onClick` – Rajat Verma Apr 19 '20 at 14:24
  • @RajatVerma I pass the props where i initialise the and the tag in the constructor – Sali Ke Apr 19 '20 at 14:35
  • Maybe this will help [Call child method from parent](https://stackoverflow.com/questions/37949981/call-child-method-from-parent) – Person Apr 20 '20 at 15:19

0 Answers0