Search code examples
sharepointsharepoint-2013web-parts

"this" undefined in React component event handler


When the user clicked submit button I need to bind these input fields to an instance of Message interface, to do this I created an Message object in class
and set the values of input values in form(keepNameUpdated()).

When I type something it throws

Uncaught TypeError: Cannot read property 'message' of undefined

so it says "this" is undefined, but why?

here is my code:

     export class IMessage {
          Name: string;
          Surname: string;
        }



     export default class Contact extends React.Component<IContactProperties, IWebPartState> {
        message : IMessage;
        constructor(props: IContactProperties, state: IWebPartState) {
            super(props);
            this.message = new IMessage();
        }
 public render(): JSX.Element {
            return (
                 <div className="row">
                    <div className="form-group col-md-6">
                        <label >Name</label>
                        <input type="text" className="form-control" onChange={this.keepNameUpdated} id="name" placeholder="Adiniz" />
                      </div>
                      <div className="form-group col-md-6">
                        <label >Surname</label>
                        <input type="text" className="form-control" id="surname" placeholder="Soyadiniz" />
                      </div>
                      <div className="form-group col-md-12">
                        <button type="button" className="btn btn-success" onClick={this.clickSubmit}><i className="fa fa-save"></i> Submit</button>
                      </div>
                  </div>
                );
    }

        private keepNameUpdated(e) {
            this.message.Name=e.target.value;
          }
          private keepSurnameUpdated(e) {
            this.message.Surname=e.target.value;
          }

why this reference is undefined ? enter image description here


Solution

  • IIRC, you have to bind the handler functions so that their notion of this refers to the instance of the React component. So, in your constructor, add these lines:

    this.keepNameUpdated = this.keepNameUpdated.bind(this); this.keepSurnameUpdated = this.keepSurnameUpdated.bind(this);

    Source: https://facebook.github.io/react/