Whymess
Whymess

Reputation: 717

holding onto events while mapping over an object

Below I am looping over an object, that contains a bunch of questions. When the object is rendered, with the question and input tag the on change event handler breaks. Thoughts?

    convertPropsIntoObject(){

    var obj = this.state.questionMap
    var data = _.map(obj, function(value, prop) {
        return (
             <div className="field" key={uuidv4()}>
                <label className="label">{prop}
                </label>
              <div className="control">
                  <textarea 
                      className="textarea" 
                      placeholder={'Enter your response here'}  
                      defaultValue={value}
                      onChange={e => this.handleChange}
                      />
              </div>
            </div>

            )

    });

    return (
        <form onSubmit={e => this.handleSubmit(e)}>
            {data}
        <button className="button is-success is-outlined">Resubmit your responses</button>
        </form>

        )



}

This is my error

   TypeError: Cannot read property 'handleChange' of undefined
onChange
src/Components/CompletedSubmission/CompletedIceBreakerForm.js:40
  37 |            className="textarea" 
  38 |            placeholder={'Enter your response here'}  
  39 |            defaultValue={value}
> 40 |            onChange={e => this.handleChange()}
  41 |            />
  42 |    </div>
  43 | </div>

Upvotes: 0

Views: 21

Answers (1)

Danny Delott
Danny Delott

Reputation: 7008

The callback to _.map is called from within a different execution context, so the this keyword will be referring to lodash.

Use an arrow function instead for implicit this binding:

var data = _.map(obj,(value, prop) => { ... });

Upvotes: 2

Related Questions