README
use-input-file
A React hook that allows you to handle HTML <input type="file">
.
DEMO
Installation
$ yarn add use-input-file
Basic Usage
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}>
)
};
ref
Passing Custom 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}>
)
};
Setting Input Options
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/*">
onChange
Callback
The 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 });
API
const { ref, file } = useInputFile({/* ...options */});
Hook Parameters
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. |
Return Values
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. |
Tests
$ make test
Lint
$ make lint
License
MIT © Peng Jie