A React hook that allows you to handle HTML <input type="file">
.
$ yarn add use-input-file
import React, { useEffect } from 'react';
import useInputFile from 'use-input-file';
const App () => {
const { ref, files } = useInputFile();
// Check your upload files changed
useEffect(() => {
console.log(files);
}, [files]);
return (
<input ref={ref}>
)
};
import React, { useEffect, useRef } from 'react';
const App () => {
const ref = useRef(null);
const { files } = useInputFile({ ref });
// Check your upload files
useEffect(() => {
console.log(files);
}, [files]);
return (
<input ref={ref}>
)
};
You can set input file attributes by options
:
const options = { multiple: true, accept: 'image/*' };
const { ref, files } = useInput({ options });
// render: <input type="file" multiple="multiple" accept="image/*">
As above, the hook default will return empty files
, when the input file changed will return new files
with your changed.
Sometimes you may want to custom onChange for your logic, so you can pass onChange
callback argument to hook
and handle input file change for you want.
const onChange = event => {
// Doing something...
console.log(event.currentTarget.files);
};
const { ref } = useInputFile({ onChange });
const { ref, file } = useInputFile({/* ...options */});
You can configure use-input-file
via the below parameters:
Key | Type | Default | Description |
---|---|---|---|
ref | React.RefObject | React.RefObject<HTMLInputElement> |
Passing your custom ref . |
options | object | { accept: string, multiple: boolean } |
Check MDN - input type="file" for more details. |
onChange | function | You can pass onChange callback argument to hook and handle input file change for you want. |
Key | Type | Default | Description |
---|---|---|---|
ref | React.RefObject | React.RefObject |
The react ref . |
files | array | [] |
The hook default will return empty File, when the input file changed will return new File with your changed. |
$ make test
$ make lint
MIT © Peng Jie