question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Simple file input example

See original GitHub issue

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.

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

interface Props extends InputHTMLAttributes<HTMLInputElement> {
  name: string
}

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

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).

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 <FileField name="files" />:

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.

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:93
  • Comments:15

github_iconTop GitHub Comments

8reactions
mmoocommented, Dec 17, 2019

Wow thank you! You saved my life.

Looks hacky enough to not be added to the official docs though. I think the lib should have it implemented as a feature instead.

3reactions
MadikMayCrycommented, Jan 11, 2021

Can you add remove icon for deleting from file list array please

Read more comments on GitHub >

github_iconTop Results From Across the Web

<input type="file"> - HTML: HyperText Markup Language | MDN
A file input's value attribute contains a string that represents the path to the selected file(s). If no file is selected yet, the...
Read more >
Bootstrap File Input Basic Usage Demo - © Kartik
Basic Example 1. Automatically convert a file input to a bootstrap file input widget by setting its class as file . Note that...
Read more >
Bootstrap File Input - examples & tutorial
Bootstrap file input is a field which user can use to upload one or more files (photos, documents or any other file type)...
Read more >
HTML input type="file" - W3Schools
The <input type="file"> defines a file-select field and a "Browse" button for file uploads. To define a file-select field that allows multiple files...
Read more >
2. Simple File Input - * arachnoid.com
Simple File Input. C++ programs can read and write files in many ways. ... This example will print a line followed by two...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found