final-form / final-form/react-final-form

Simple file input example

Open
#663 16 comments 104 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
7.4k
Forks
497
PR merge metrics
No merged PRs in 30d

Description

There are no examples in the documentation about file inputs, and the issues advise to use react-dropzone, which is overkill if I just want a simple file input.

So I just wanted to share a TypeScript snippet that can be used for file inputs, especially if you want to have a `File` in your field value (instead of that useless _fakepath_ given by the input `value`), if you want to create a `FormData` for example.

```tsx
import type { InputHTMLAttributes } from "react"
import { Field } from "react-final-form"

interface Props extends InputHTMLAttributes {
name: string
}

const FileField = ({ name, ...props }: Props) => (
name={name}>
{({ input: { value, onChange, ...input } }) => (
onChange(target.files)} // instead of the default target.value
{...props}
/>
)}

)
```

The trick is to just replace the default `change` event behavior by giving it the `files` attribute instead of the `value`, and leave the input uncontrolled since we extract and ignore the `value` ([this is normal for file inputs](https://reactjs.org/docs/uncontrolled-components.html#the-file-input-tag)).

Then in your `onSubmit` handler, you will have a `FileList` as the field `value`, so you can iterate over it (or just read the first element if it's not a `multiple` file input) and add each `File` to your `FormData`, e.g. if you form has a ``:

```tsx
const handleSubmit = async (values: Values) => {
const payload = new FormData()
payload.append("file", values.files[0])
// you can also add the rest of your form text data, e.g.:
payload.append("firstname", "Antoine")
payload.append("lastname", values.lastname)
// and then just post it to your API using a regular POST:
await fetch(YOUR_URI, {
method: "POST",
body: payload, // this sets the `Content-Type` header to `multipart/form-data`
})
}
```

See it in action: https://codesandbox.io/s/react-final-form-file-field-ffugr

Related issues:
#24
#92

If you like this example, I can make a PR to add it to the docs.
Or it could be the default behavior of the lib for file inputs.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.