Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SUGGESTION] Create a File Control component #156

Open
Byevenes opened this issue Aug 23, 2022 · 0 comments
Open

[SUGGESTION] Create a File Control component #156

Byevenes opened this issue Aug 23, 2022 · 0 comments

Comments

@Byevenes
Copy link

import React, { ChangeEvent, ForwardedRef, useRef } from 'react'
import { EditIcon } from '@chakra-ui/icons'
import { Button, ButtonProps, InputGroup } from '@chakra-ui/react'
import { useField } from 'formik'

import { SUPPORTED_FORMATS } from 'utils/yup'

import FormControl, { BaseProps } from '../FormControl'

type FileUploadProps = {
  accept?: string
  multiple?: boolean
}

export type FileControlProps = BaseProps & FileUploadProps & { buttonProps?: ButtonProps };

export const FileControl: React.FC<FileControlProps> = React.forwardRef(
  (props: FileControlProps, ref: ForwardedRef<HTMLInputElement>) => {
    const { name, label, buttonProps, multiple = false, accept = SUPPORTED_FORMATS.join(' ,'), ...rest } = props
    const [{ onChange, ...field }, , { setValue }] = useField(name)
    const inputRef = useRef<HTMLInputElement | null>(null)

    const handleClick = () => {
      inputRef.current?.click()
    }

    const handleChange = (value: ChangeEvent<HTMLInputElement>) => {
      value.target.files && setValue(value.target.files?.[0])
    }

    return (
      <FormControl name={name} label={label} {...rest} {...ref}>
        <InputGroup onClick={handleClick}>
          <input
            onChange={handleChange}
            type='file'
            accept={accept}
            multiple={multiple}
            id={name}
            ref={inputRef}
            hidden />
          <Button w={'full'} variant={'secondary'} {...buttonProps} {...field} leftIcon={<EditIcon />} isLoading={false} paddingX={24}>
            {'Adjuntar'}
          </Button>
        </InputGroup>
      </FormControl>
    )
  }
)

export default FileControl
@Byevenes Byevenes changed the title Create a File Control component [SUGGESTION] Create a File Control component Aug 23, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant