0.1.21 • Published 3 years ago

react-avatar-selector v0.1.21

Weekly downloads
-
License
ISC
Repository
github
Last release
3 years ago

React Avatar Selector

Installation and usage

Install from npm:

npm i --save react-avatar-selector

Then use it in your app:

import React from 'react'
import AvatarSelector from 'react-avatar-selector'

function App(){
  const [pic, setPic] = React.useState(null)

  return (
    <AvatarSelector onChange={(value) => setPic(value)} value={pic} />
  )
}

File data format

This is an example object that is retrieved by the onChange prop, and the same object that should be passed as the value prop.

const value = {
  name: "me_profile.jpeg",
  type: "image/jpeg",
  size: "840 kB",
  base64: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEASABIAAD/...",
}

Props

Common props you may want to include:

PropRequirementDefault ValueDescription
onChangeRequired(value) => nullCallback function, will recieve the image object as a value
valueRequiredundefinedThe object given by the onChange handler
sizeOptional200Type number, defines the size of the element in pixels
iconSizeOptionalsize / 5Type number, defines the size of the (camera) icon in pixels

Additional imports

readFile (function)

This function translates the selected file from your input into the "FileData" object, can be used if you choose your own file selection input, but don't want to handle the FileReader API and/or format the data.

import React from 'react
import {readFile} from 'react-avatar-selector'

function App(){
  const [pic, setPic] = React.useState(null)

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    readFile(e, (file) => {
      setPic(file)
    })
  }

  return (
    <input type="file" onChange={handleChange} />
  )
}

FileData (TypeScript)

The interface representing the object cointaining the image file data.

interface FileData {
  name: string
  type: string
  size: string
  base64: string
}

Usage:

import AvatarSelector, {FileData} from 'react-avatar-selector'

function App(){
  const [pic, setPic] = React.useState<FileData | null>(null)

  return (
    <AvatarSelector onChange={(value: FileData) => setPic(value)} value={pic} />
  )
}