2

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

import UserInput from './learn/UserInput';


class App extends Component {


  state = {
    users : [
      {id:1, name:'manu', Age:28},
      {id:2,name:'john', Age:29},
      {id:3,name:'clint', Age:30},
    ]
  }


changeMethod = (event, id) => {

  const userIndex = this.state.users.findIndex( 
      (el) => {
      return  el.id === id;
      }

    ) 

  const user = {
    ...this.state.users[userIndex]
  };

  user.name = event.target.value;

  const users = [...this.state.users];

  users[userIndex] = user;

  this.setState({
    users : users
  })
}




  render() {

      let persons = (
           <div>

            {this.state.users.map( (el, index) => { 

              return (
                <div key ={el.id}>
                <p>{el.name}</p>

                <input type="text" name="" id="" onChange={this.changeMethod.bind(this, el.id)} 
                  value ={el.name}
                  />

                  </div>
              )
              })}

          </div> 
      )


    return (

        <div className="App">
            {persons}
        </div>

    );
  }
}

export default App;

this is the error im getting when i try to enter in the input box

TypeError: Cannot read property 'value' of undefined
App._this.changeMethod
src/App.js:33
  30 |   ...this.state.users[userIndex]
  31 | };
  32 | 
> 33 | user.name = event.target.value;
  34 | 
  35 | const users = [...this.state.users];

1 Answer 1

2

This is because you bound the onChange function like this:

onChange={this.changeMethod.bind(this, el.id)}

So in changeMethod method first argument will always be id, then you will get the event object.

Write the changeMethod like this:

changeMethod = (id, event) => {
   ....
}

Why you are getting the error: "Can't read property value of undefined"?

Because, in your case event (just an the argument name) will be a value (id that you passed), and event.target will be undefined, that's why "Can't read ......".

As per MDN Doc:

function.bind(thisArg[, arg1[, arg2[, ...]]])

arg1, arg2, ... Arguments to prepend to arguments provided to the bound function when invoking the target function.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.