Skip to content

Instantly share code, notes, and snippets.

@archiewald
Last active January 20, 2019 13:38
Show Gist options
  • Save archiewald/582cd43cf1f4910afe2f1a064b01b953 to your computer and use it in GitHub Desktop.
Save archiewald/582cd43cf1f4910afe2f1a064b01b953 to your computer and use it in GitHub Desktop.
[Function as Children] #react #javascript

Used in react-dropzone docs

import React from 'react'
import classNames from 'classnames'
import Dropzone from 'react-dropzone'

class MyDropzone extends React.Component {
   onDrop = (acceptedFiles, rejectedFiles) => {
     // Do something with files
   }

   render() {
    return (
      <Dropzone onDrop={this.onDrop}>
        {({getRootProps, getInputProps, isDragActive}) => {
          return (
            <div
              {...getRootProps()}
              className={classNames('dropzone', {'dropzone--isActive': isDragActive})}
            >
              <input {...getInputProps()} />
              {
                isDragActive ?
                  <p>Drop files here...</p> :
                  <p>Try dropping some files here, or click to select files to upload.</p>
              }
            </div>
          )
        }}
      </Dropzone>
    );
  }
}

How it works? render function in source code:

 render() {
    const { children, multiple, disabled } = this.props
    const { isDragActive, isFocused, draggedFiles, acceptedFiles, rejectedFiles } = this.state

    const filesCount = draggedFiles.length
    const isMultipleAllowed = multiple || filesCount <= 1
    const isDragAccept = filesCount > 0 && allFilesAccepted(draggedFiles, this.props.accept)
    const isDragReject = filesCount > 0 && (!isDragAccept || !isMultipleAllowed)

    return children({
      isDragActive,
      isDragAccept,
      isDragReject,
      draggedFiles,
      acceptedFiles,
      rejectedFiles,
      isFocused: isFocused && !disabled,
      getRootProps: this.getRootProps,
      getInputProps: this.getInputProps,
      open: this.open
    })
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment