Skip to content

Instantly share code, notes, and snippets.

@wjuniorw
Last active March 8, 2021 01:23
Show Gist options
  • Select an option

  • Save wjuniorw/a407bad8cc726478adad7931036c9079 to your computer and use it in GitHub Desktop.

Select an option

Save wjuniorw/a407bad8cc726478adad7931036c9079 to your computer and use it in GitHub Desktop.
import { useState } from 'react'
// custom hook .................useFile..........................
const useInputFile = () => {
const [file, setValue] = useState('')
function getBase64({target}) {
const fileToLoad = target.files[0]
const FR = new FileReader()
FR.onload = (event) => {
return setValue(event.target.result)
}
FR.readAsDataURL(fileToLoad)
}
return [ file, getBase64 ]
}
export default useInputFile
// como usar:...........custom input....................
import React, { useEffect } from 'react'
import useFile from '../hooks/useFile'
export default ({ onChange }) => {
const [ file, getBase64 ] = useFile()
useEffect(()=> {
onChange({ target: {name: 'image', value: file}})
}, [file])
return (
<div className="">
<h4 className="">Escolha uma imagem</h4>
<div className="">
<input
type="file"
onChange={(bs64) => getBase64(bs64)}
/>
</div>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment