Search code examples
javascriptreactjsimage-uploadreact-stateinput-type-file

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?


Solution

  • 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')}/>