01
How do you upload a file with a preview in React?
Show answer
Use a file input, create a preview URL and send FormData.
function AvatarUpload() {
const [file, setFile] = useState(null);
const preview = useMemo(() => file && URL.createObjectURL(file), [file]);
useEffect(() => () => preview && URL.revokeObjectURL(preview), [preview]);
async function upload() {
const fd = new FormData();
fd.append('avatar', file);
await fetch('/api/avatar', { method: 'POST', body: fd });
}
return (<>
<input type="file" accept="image/*" onChange={e => setFile(e.target.files[0])} />
{preview && <img src={preview} alt="preview" />}
<button onClick={upload}>Upload</button>
</>);
}