user12500870
user12500870

Reputation:

how to add onchange event in react js application

I am new to reactjs I want to add onchange in my application. I am using map function for data.

onChange = (event,k,i) => {
     this.setState({

      dList: update(this.state.dList[k][i], {
        [event.target.name]:
          {$set: event.target.value} 
      })
    })
  }

Upvotes: 1

Views: 937

Answers (3)

okumu justine
okumu justine

Reputation: 368

state example

state = {
    name:'',
    password:''
}

Incase you have multiple inputs of example name and password

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

<input type="password" name="password" value={password} onChange={this.handleChange} />

this how you apply the onchange handler

handleChange = e => {
    this.setState({[e.target.name]: e.target.value})
}

Upvotes: 1

Ajay Ullal
Ajay Ullal

Reputation: 378

If you want to update your component's state which depends on the previous state of the component, use the overloaded version of setState which takes a function as a parameter. This is because the calls made to the setState function are batched to improve performance.

onChange = (event,k,i) => {
     this.setState(prevState => {
      dList: update(prevState.dList[k][i], {
        [event.target.name]:
          {$set: event.target.value} 
      })
    })
} 

Upvotes: 0

Matvii Hodovaniuk
Matvii Hodovaniuk

Reputation: 513

You should put an onChange function in a onChange html tag attribute.

Example:

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

Reference

Upvotes: 0

Related Questions