|
| 1 | +import { DjangoFormProps } from "./types"; |
| 2 | +import React from "react"; |
| 3 | +import ReactDOM from "react-dom"; |
| 4 | +/** |
| 5 | + * Interface used to bind a ReactPy node to React. |
| 6 | + */ |
| 7 | +export function bind(node) { |
| 8 | + return { |
| 9 | + create: (type, props, children) => |
| 10 | + React.createElement(type, props, ...children), |
| 11 | + render: (element) => { |
| 12 | + ReactDOM.render(element, node); |
| 13 | + }, |
| 14 | + unmount: () => ReactDOM.unmountComponentAtNode(node), |
| 15 | + }; |
| 16 | +} |
| 17 | + |
| 18 | +export function DjangoForm({ |
| 19 | + onSubmitCallback, |
| 20 | + formId, |
| 21 | +}: DjangoFormProps): null { |
| 22 | + React.useEffect(() => { |
| 23 | + const form = document.getElementById(formId) as HTMLFormElement; |
| 24 | + |
| 25 | + // Submission event function |
| 26 | + const onSubmitEvent = (event) => { |
| 27 | + event.preventDefault(); |
| 28 | + const formData = new FormData(form); |
| 29 | + |
| 30 | + // Convert the FormData object to a plain object by iterating through it |
| 31 | + // If duplicate keys are present, convert the value into an array of values |
| 32 | + const entries = formData.entries(); |
| 33 | + const formDataArray = Array.from(entries); |
| 34 | + const formDataObject = formDataArray.reduce((acc, [key, value]) => { |
| 35 | + if (acc[key]) { |
| 36 | + if (Array.isArray(acc[key])) { |
| 37 | + acc[key].push(value); |
| 38 | + } else { |
| 39 | + acc[key] = [acc[key], value]; |
| 40 | + } |
| 41 | + } else { |
| 42 | + acc[key] = value; |
| 43 | + } |
| 44 | + return acc; |
| 45 | + }, {}); |
| 46 | + |
| 47 | + onSubmitCallback(formDataObject); |
| 48 | + }; |
| 49 | + |
| 50 | + // Bind the event listener |
| 51 | + if (form) { |
| 52 | + form.addEventListener("submit", onSubmitEvent); |
| 53 | + } |
| 54 | + |
| 55 | + // Unbind the event listener when the component dismounts |
| 56 | + return () => { |
| 57 | + if (form) { |
| 58 | + form.removeEventListener("submit", onSubmitEvent); |
| 59 | + } |
| 60 | + }; |
| 61 | + }, []); |
| 62 | + |
| 63 | + return null; |
| 64 | +} |
0 commit comments