Cj Oyales
Cj Oyales

Reputation: 302

Im getting an unnamed state after onChange in input type file - ReactJS

I'm using input type file to upload images to strapi.io. I noticed that in the state on the react dev tools it generate a unnamed state seen in the image below.

enter image description here

state

constructor(props) {
    super(props);
    this.state = {
      first_name: '',
      last_name: '',
      address: '',
      email:'',
      city: '',
      country: '',
      zipcode: '',
      gcash_number: '',
      paypal_email: '',
      error: '', 
      bank_account: '',
      bank_name: ''
    }
    this.handleOnChange = this.handleOnChange.bind(this)
  }

JSX

<div className='col-sm-auto'>
  <label htmlFor='avatar' >Avatar</label>
   <input type='file' className="form-control-file form-control-sm" onChange={this.handleOnChange('avatar')}/>            
</div>

handleOnChange function

handleOnChange = input => (event) => {
    if (event.target.type === 'file') {
      this.setState({avatars: event.target.files[0]})
    }
    this.setState({
      [event.target.name]: event.target.value
    })
  }

can some explain to me how this happened? and how to put a state name on that?

Upvotes: 0

Views: 115

Answers (2)

mohamed ibrahim
mohamed ibrahim

Reputation: 583

It's better to define an id for the input element:

<input id="InputID" type='file' className="form-control-file form-control-sm" onChange={this.handleOnChange('avatar')}/>

Because you used htmlFor in the label tag And try the following code :

this.setState({ [event.target.id]: event.target.value });

Upvotes: 0

Karl Lopez
Karl Lopez

Reputation: 1099

this.setState({
    [event.target.name]: event.target.value
});

name is undefined

Try

<input name="myInputName" type='file' className="form-control-file form-control-sm" onChange={this.handleOnChange('avatar')}/>  

Upvotes: 2

Related Questions