Simple file input example
See original GitHub issueThere 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
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:
- Created 4 years ago
- Reactions:93
- Comments:15
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.
Can you add remove icon for deleting from file list array please