Reactjs – Call parent method in child component

Good evening.

I start to learn reactj. I try to make a form that can have personalized content but I try to call a method in the form’s parent class where I try to change a state variable but it say “Cannot read property ‘test’ of undefined”.

My form class :

class Test extends React.Component {

    constructor (props) {
         super(props)
    }

    tmp(e) {
        this.props.functionTest(e);
    }

    render() {
        return(
            <div className={this.props.DivFormClass}>
                <div className={this.props.TitleClass}>
                    {this.props.Title}
                </div>
                <form className={this.props.FormClass} onSubmit={e => this.tmp(e)}>
                    {this.props.children}
                </form>
            </div>
        )
    }
}

The parent class :

class Formtest extends React.Component {
    constructor (props) {
        super(props)
        this.state = {
            test :"ok"
        }
    }

    FunctionTest (e) {
        e.preventDefault();
        console.log(this.state.test)
    }

    render() {
        return (
            <div>
                <Test DivFormClass="divtest" TitleClass="titletest" FormClass="test" Title="Test Form" functionTest={this.FunctionTest}>
                    <input name="email" type="email" required="required" className="error"/>
                    <button>OK</button>
                </Test>
            </div>
        )
    }
}

What am I doing wrong ?

Answer

convert this function to arrow function

FunctionTest  = (e) => {
    e.preventDefault();
    console.log(this.state.test)
}

or use the bind statement to bind the value of this to class not to function itself

Leave a Reply

Your email address will not be published. Required fields are marked *