Comments (4)
@KyuubiTila
To fix this issue and correctly handle file uploads, you can make use of the onFileChange
function provided by Formik. Here's how you can modify your CreateProductCard
component to handle file uploads correctly:
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
const CreateProductCard = ({ addProduct, initialValues, validationSchema }) => {
return (
<Formik
initialValues={initialValues}
onSubmit={(data, params) => {
console.log(data);
// addProduct(data);
// params.resetForm();
}}
validationSchema={validationSchema}
>
{({ setFieldValue }) => (
<Form>
{/* ... other form fields ... */}
<div className="mb-6">
<label
htmlFor="image"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
IMAGE
</label>
<input
type="file"
name="image"
accept=".jpg, .jpeg, .png, .gif"
className="block w-full"
onChange={(event) => {
// Set the field value to the selected file
setFieldValue("image", event.currentTarget.files[0]);
}}
/>
<ErrorMessage name="image" component="div" className="text-red-500" />
</div>
<button
type="submit"
className="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
>
CREATE PRODUCT
</button>
</Form>
)}
</Formik>
);
};
export default CreateProductCard;
from formik.
still no way out, formik seems to not be sending the image as a file object.
from formik.
yeahhh so here is the solution that works. Just figured it out
FIRST THING TO DO
You can create one component like this, just a raw component.
import React from 'react';
function FileUpload(props) {
const {field, form} = props;
const handleChange = (e) => {
const file = e.currentTarget.files[0];
const reader = new FileReader();
const imgTag = document.getElementById("myimage");
imgTag.title = file.name;
reader.onload = function(event) {
imgTag.src = event.target.result;
};
reader.readAsDataURL(file);
form.setFieldValue(field.name, file);
};
return (
<input type={'file'} onChange={(o) => handleChange(o)} className={'form-control'}/>
<img src={''} alt="" id={'myimage'}/>
);
}
export default FileUpload;
SECONDLY, IMPORT IN YOUR FORMIK CONTROLLED FORM
And use this like this inside the form
<Field
name="image"
component={FileUpload} // import from the component you just created above
/>
SOLUTION CREDIT : Sonukr, on Apr 14, 2019
from formik.
Ths is what my code looks like
'use client';
import React from 'react';
import { Formik, Form, Field } from 'formik';
import FileUpload from '@/components/fileupload';
const UpdateProfile = () => {
const initialValues = {
username: '',
bio: '',
profilePhoto: '',
};
const handleSubmit = (values) => {
console.log('Form values:', values);
};
return (
{({ isSubmitting }) => (
Update Profile
<div className="relative flex items-center mt-2">
<Field
type="text"
name="username"
className="block w-full py-3 text-gray-700 bg-white border rounded-lg px-6 dark:bg-gray-900 dark:text-gray-300 dark:border-gray-600 focus:border-blue-400 dark:focus:border-blue-300 focus:ring-blue-300 focus:outline-none focus:ring focus:ring-opacity-40"
placeholder="Username"
/>
</div>
<label
htmlFor="profilePhoto"
className="flex items-center px-3 py-3 mx-auto mt-6 text-center bg-white border-2 border-dashed rounded-lg cursor-pointer dark:border-gray-600 dark:bg-gray-900"
>
<h2 className="mx-3 text-gray-400">Profile Photo</h2>
<Field name="image" component={FileUpload} />
</label>
<div className="relative flex items-center mt-6">
<Field
as="textarea"
name="bio"
className="block w-full py-3 text-gray-700 bg-white border rounded-lg px-6 dark:bg-gray-900 dark:text-gray-300 dark:border-gray-600 focus:border-blue-400 dark:focus:border-blue-300 focus:ring-blue-300 focus:outline-none focus:ring focus:ring-opacity-40"
placeholder="Bio"
/>
</div>
<div className="mt-6">
<button
type="submit"
className="w-full px-6 py-3 text-sm font-medium tracking-wide text-white capitalize transition-colors duration-300 transform bg-blue-500 rounded-lg hover:bg-blue-400 focus:outline-none focus:ring focus:ring-blue-300 focus:ring-opacity-50"
disabled={isSubmitting}
>
{isSubmitting ? 'Updating...' : 'Update Profile'}
</button>
</div>
</Form>
)}
</Formik>
</div>
</section>
);
};
export default UpdateProfile;
and the component
import React from 'react';
function FileUpload(props) {
const { field, form } = props;
const handleChange = (e) => {
const file = e.currentTarget.files[0];
const reader = new FileReader();
const imgTag = document.getElementById('myimage');
imgTag.title = file.name;
reader.onload = function (event) {
imgTag.src = event.target.result;
};
reader.readAsDataURL(file);
form.setFieldValue(field.name, file);
};
return (
<input
type={'file'}
onChange={(o) => handleChange(o)}
className={'form-control'}
/>
<img src={''} alt="" id={'myimage'} />
);
}
export default FileUpload;
from formik.
Related Issues (20)
- onPaste + setFieldValue does not work as intended HOT 2
- Get validating state of individual components
- Page reloads on submit if form is inside drawer component HOT 5
- Margin not added in UI HOT 3
- Uncaught (in promise) TypeError: e2 is null [CoreValidator.ts:138:2]
- Why do I have to specify a name again when using useField's onChange function?
- Support for React Native's SyntheticEvent type HOT 1
- Consider shipping a LICENSE file with your npm package HOT 1
- useField's onChange function should accept non-string values as args
- Formik.dirty is not reacting to nested changes HOT 1
- Docs layout is a bit broken HOT 4
- React Native form resets to initial values HOT 2
- Terneries, espescially deeply nested ternaries, make code difficult to read. Please do not do this. HOT 1
- RangeError: Maximum call stack size exceeded HOT 1
- Call formik.setFieldValue() with previous value as parameter
- Formik Validation HOT 1
- How to validate few fields (not all) on type button click in yup and formik. HOT 2
- enableReinitialize doesn't work anymore HOT 2
- Formik form actions cannot be used on nextjs server actions HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from formik.