Code Monkey home page Code Monkey logo

Comments (4)

Janelaxagh avatar Janelaxagh commented on June 1, 2024

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

KyuubiTila avatar KyuubiTila commented on June 1, 2024

still no way out, formik seems to not be sending the image as a file object.

from formik.

KyuubiTila avatar KyuubiTila commented on June 1, 2024

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

Screen Shot 2024-02-11 at 19 08 57

from formik.

KyuubiTila avatar KyuubiTila commented on June 1, 2024

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;

AND HERE IS THE RESULT:
Screen Shot 2024-02-11 at 19 13 09

from formik.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.