How to upload file with redux-form?

Mike Doudkin picture Mike Doudkin · Sep 26, 2016 · Viewed 28.5k times · Source

I can't get correct value into the store when trying to upload a file. Instead of file content, I get something like { 0: {} }. Here's the code:

const renderInput = field => (
  <div>
    <input {...field.input} type={field.type}/>
    {
      field.meta.touched &&
      field.meta.error &&
      <span className={styles.error}>{field.meta.error}</span>
    }
  </div>
);

render() {

  ...

  <form className={styles.form} onSubmit={handleSubmit(submit)}>
    <div className={styles.interface}>
      <label>userpic</label>
      <Field
        name="userpic"
        component={renderInput}
        type="file"
      />
    </div>
    <div>
      <button type="submit" disabled={submitting}>Submit</button>
    <div>
  </form>

  ...

}

All the examples on the web that I found were made using v5 of redux-form.

How do I do file input in redux-form v6?

Answer

bh4r4th picture bh4r4th · Oct 26, 2017

Create a Field Component like:

import React, {Component} from 'react'

export default class FieldFileInput  extends Component{
  constructor(props) {
    super(props)
    this.onChange = this.onChange.bind(this)
  }

  onChange(e) {
    const { input: { onChange } } = this.props
    onChange(e.target.files[0])
  }

  render(){
    const { input: { value } } = this.props
    const {input,label, required, meta, } = this.props  //whatever props you send to the component from redux-form Field
    return(
     <div><label>{label}</label>
     <div>
       <input
        type='file'
        accept='.jpg, .png, .jpeg'
        onChange={this.onChange}
       />
     </div>
     </div>
    )
}
}

Pass this component to the Field component where you needed. No need of additional Dropzone or other libraries if you are after a simple file upload functionality.