jaredpalmer / formik

Build forms in React, without the tears 😭
https://formik.org
Apache License 2.0
33.97k stars 2.79k forks source link

How to create a add image input in formik #2553

Open mayankk2153 opened 4 years ago

mayankk2153 commented 4 years ago

I want to create a customized input field in formik for an image upload. I want to pass binary file data to backend, but it is taking the file location. Can you help me?

Here is the boilerplate code:

import React from 'react';
import { useField } from 'formik';
import { Form, Col, Row } from 'react-bootstrap';

const FileInput = ({ label, ...props }) => {
  const [field, meta] = useField(props);
  return (
    <>
      <Form.Group as={Row} controlId="">
        <Form.Label htmlFor={props.id || props.name} column sm={3}>
          {label}
        </Form.Label>
        {props.initalImage ? (
          <img height="35px" alt={props.initalImage} src={props.initalImage} />
        ) : null}
        <Col sm={4}>
          <Form.Control
            {...field}
            {...props}
            accept={props.accept}
            isValid={meta.touched && !meta.error}
            isInvalid={Boolean(meta.touched && meta.error)}
          />
          {meta.error ? (
            <>
              <Form.Control.Feedback type="invalid">
                {meta.error}
              </Form.Control.Feedback>
            </>
          ) : null}
          <span className="form-text text-muted mt-3">
            Please choose an icon which is min. 256x256px.
          </span>
        </Col>
      </Form.Group>
    </>
  );
};
export { FileInput };

and here is where I am calling it:

        <FileInput
          label="Light Icon:"
          type="file"
          name="lightIcon"
          accept="image/x-png"
          onBlur
        />

I tried this but it is not working:

    <FileInput
      label="Light Icon:"
      type="file"
      name="lightIcon"
      accept="image/x-png"
      onBlur
      onChange={(e) => {
        setFieldValue('lightIcon', e.target.files[0]);
      }}
    />
Svarto commented 4 years ago

Would recommend you to read this closed issue: #45