1.0.5 • Published 4 years ago
use-input-file v1.0.5
use-input-file
A React hook that allows you to handle HTML <input type="file">.
DEMO
Installation
$ yarn add use-input-fileBasic 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}>
)
};Passing Custom 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}>
)
};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/*">The onChange Callback
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 testLint
$ make lintLicense
MIT © Peng Jie
1.0.5-beta.1
4 years ago
1.0.5
4 years ago
1.0.4-beta.0
4 years ago
1.0.4
4 years ago
1.0.3
5 years ago
1.0.3-beta.1
5 years ago
1.0.2
5 years ago
1.0.1
5 years ago
1.0.0
5 years ago