0

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 ?

  • Does this answer your question? [How to pass data from child component to its parent in ReactJS?](https://stackoverflow.com/questions/38394015/how-to-pass-data-from-child-component-to-its-parent-in-reactjs) – Gh05d Mar 08 '21 at 14:21
  • https://stackoverflow.com/questions/40109698/react-call-parent-method-in-child-component it is duplicated – mansoureh.hedayat Mar 08 '21 at 14:22

1 Answers1

0

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

Raj D
  • 485
  • 1
  • 5
  • 11