Search code examples
javascriptreactjsreact-propsreact-statereact-dropzone

Accessing props in onSubmit method of react-dropzone-uploader


I am using react-dropzone-uploader to upload files. Everything works OK; except that I want the parent Component to be updated after clicking on submit button. What should I do?

This is the part of code I use:


export default () => {

  const handleSubmit = (files, allFiles) => {
    console.log('uploads files:', files, this)
    // There is no access to props here.
  }

  return (
    <Dropzone
      getUploadParams={getUploadParams}
      onChangeStatus={handleChangeStatus}
      onSubmit={handleSubmit}
      accept="image/*,.pdf,.doc,.docx"
    />
  )
}

Solution

  • As it is a functional component you don't need this and you get props from

    export default (props) => {
    
      const handleSubmit = (files, allFiles) => {
        console.log('uploads files:', files)
        // Get set state function from props
        props.setFiles(files)
      }
    
      return (
        <Dropzone
          getUploadParams={getUploadParams}
          onChangeStatus={handleChangeStatus}
          onSubmit={handleSubmit}
          accept="image/*,.pdf,.doc,.docx"
        />
      )
    }
    

    And in the parent, you can call this component as

    ...
    const [files, setFiles] = useState(null)
    ...
    return (
      <div>
      <div>Drop files</div>
      <CustomDropzone setFiles={setFiles} />
      </div>
    )