1.0.5 • Published 2 years ago

use-input-file v1.0.5

Weekly downloads
11
License
MIT
Repository
github
Last release
2 years ago

use-input-file

CI npm minified + gzip styled with prettier

A React hook that allows you to handle HTML <input type="file">.

DEMO

Edit

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}>
  )
};

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:

KeyTypeDefaultDescription
refReact.RefObjectReact.RefObject<HTMLInputElement>Passing your custom ref.
optionsobject{ accept: string, multiple: boolean }Check MDN - input type="file" for more details.
onChangefunctionYou can pass onChange callback argument to hook and handle input file change for you want.

Return Values

KeyTypeDefaultDescription
refReact.RefObjectReact.RefObjectThe react ref.
filesarray[]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

1.0.5-beta.1

2 years ago

1.0.5

2 years ago

1.0.4-beta.0

3 years ago

1.0.4

3 years ago

1.0.3

4 years ago

1.0.3-beta.1

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago