🎉 Initial commit
This commit is contained in:
57
src/index.tsx
Normal file
57
src/index.tsx
Normal 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
18
src/typings.d.ts
vendored
Normal 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 }
|
||||
}
|
Reference in New Issue
Block a user