marinetk
marinetk

Reputation: 3

How to use the same handler for different input?

I'm working on a React project, and I have some text fields in my page. I would like to be able to modify these inputs separately, while still using the same handler.

When I try to type in the input, I get the error Cannot read property 'relevant' of undefined

This is the function I created:

handleChange(type) {
   console.log(type)                // outputs "one", "two', "three" when I reload the page
   return (event, type) => {
     console.log(event)                           // output the event when I type in the input
     console.log(event.target.value)              // output the value (the letter I typed)
     console.log(type)                            // output undefined
    this.setState(prevState => ({
      userInformation : {
        ...prevState.userInformation,
        [type] : {
          relevant: this.state.userInformation[type].relevant,
          other : event.target.value
          }
        }
      }))
    }
  }

The inputs :

<input type="text" value={this.state.userInformation.one.other}  onChange={this.handleChange('one')} className="probleme" />

<input type="text" value={this.state.userInformation.two.other}  onChange={this.handleChange('two')} className="probleme" />

<input type="text" value={this.state.userInformation.three.other}  onChange={this.handleChange('three')}  className="probleme" />

The state :

this.state = {
         userInformation: {
            one: {
              relevant: [ ],
             other: '',
            },
            two: {
              relevant: [ ],
              other: '',
            },
            three: {
              relevant: [ ],
              other: '',
            }
        },

Any ideas? Thank you for your time!

Upvotes: 0

Views: 75

Answers (2)

lomse
lomse

Reputation: 4165

Update your code like this:

class MyAwesomeComponent {
  constructor(props){
     this.state = {
       one: '',
       two: '',
       three: ''
     }
  }

  handleChange = (evt)=> {
     const {name, value} = evt.target

     this.setState({...this.state, [name]: value})
  }

  render(){
     return(
         <React.Fragment>
             <input name="one" type="text" value={this.state.one}  onChange={this.handleChange} className="probleme" />

             <input name="two" type="text" value={this.state.two}  onChange={this.handleChange} className="probleme" />

             <input name="three" type="text" value={this.state.three}  onChange={this.handleChange}  className="probleme" />
         </React.Fragment>
     )
  }
}

Upvotes: 1

Thoth
Thoth

Reputation: 2276

You are calling this.state outside of the scope of your function. You must manually call it using the name, instead of this., or move this.state into your function.

Upvotes: 0

Related Questions