-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import dot from "dot-object"; | ||
import React, { FC, FormEvent, useCallback } from "react"; | ||
|
||
const getAttrs = (element: any): { name: string; value: string | boolean } => { | ||
const type = element.type; | ||
const name = element.getAttribute("name"); | ||
let value = element.value || ""; | ||
if (!type || type === "button" || type === "submit") { | ||
return { name: "", value: "" }; | ||
} | ||
if (type === "checkbox") { | ||
value = value === "on"; | ||
} | ||
return { name, value }; | ||
}; | ||
|
||
export const Form: FC< | ||
JSX.IntrinsicElements["form"] & { onSubmit: (values: any) => void } | ||
> = ({ onSubmit, children, ...props }) => { | ||
const handleSubmit = useCallback( | ||
(event: FormEvent) => { | ||
if (event) { | ||
event.preventDefault(); | ||
} | ||
const target = event.target as any; | ||
const elementsKeys = Object.keys(target.elements); | ||
|
||
const objects: any = {}; | ||
|
||
elementsKeys.forEach((key: any) => { | ||
if ([target.elements[key]].toString() === "[object RadioNodeList]") { | ||
target.elements[key].forEach((el) => { | ||
const { name, value } = getAttrs(el); | ||
if (name) { | ||
dot.set(name, value, objects, true); | ||
} | ||
}); | ||
} else { | ||
const { name, value } = getAttrs(target.elements[key]); | ||
if (name) { | ||
dot.set(name, value, objects, true); | ||
} | ||
} | ||
}); | ||
|
||
onSubmit(objects); | ||
}, | ||
[onSubmit], | ||
); | ||
|
||
return ( | ||
<form {...props} onSubmit={handleSubmit}> | ||
{children} | ||
</form> | ||
); | ||
}; | ||
|
||
export default Form; |