🎉 Initial commit

This commit is contained in:
divlo
2020-08-04 16:22:31 +02:00
commit 00f95feadf
26 changed files with 48439 additions and 0 deletions

57
src/index.tsx Normal file
View File

@ -0,0 +1,57 @@
import React, { useRef } from 'react'
export interface FormDataObject {
[key: string]: FormDataEntryValue
}
export type HandleForm = (
formData: FormDataObject,
formElement: HTMLFormElement
) => void
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
interface ReactFormProps
extends Omit<React.HTMLProps<HTMLFormElement>, 'onSubmit' | 'onChange'> {}
interface FormProps extends ReactFormProps {
onSubmit?: HandleForm
onChange?: HandleForm
}
const getFormDataObject = (formElement: HTMLFormElement): FormDataObject => {
return Object.fromEntries<FormDataEntryValue>(new FormData(formElement))
}
const Form = (props: FormProps): JSX.Element => {
const { onSubmit, onChange, children, ...rest } = props
const formRef = useRef<HTMLFormElement>(null)
const handleSubmit = (event: React.FormEvent): void => {
event.preventDefault()
if (onSubmit != null) {
const formData = getFormDataObject(formRef.current as HTMLFormElement)
onSubmit(formData, formRef.current as HTMLFormElement)
}
}
const handleChange = (): void => {
if (onChange != null) {
const formData = getFormDataObject(formRef.current as HTMLFormElement)
onChange(formData, formRef.current as HTMLFormElement)
}
}
return (
<form
ref={formRef}
onSubmit={handleSubmit}
onChange={handleChange}
{...rest}
>
{children}
</form>
)
}
export default Form

18
src/typings.d.ts vendored Normal file
View File

@ -0,0 +1,18 @@
/**
* Default CSS definition for typescript,
* will be overridden with file-specific definitions by rollup
*/
declare module '*.css' {
const content: { [className: string]: string }
export default content
}
interface SvgrComponent
extends React.StatelessComponent<React.SVGAttributes<SVGElement>> {}
declare module '*.svg' {
const svgUrl: string
const svgComponent: SvgrComponent
export default svgUrl
export { svgComponent as ReactComponent }
}