Skip to content

Commit 168a727

Browse files
committed
Client side form handler
1 parent c8b4ec0 commit 168a727

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/js/src/index.tsx

+46
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,21 @@ import { ReactPyDjangoClient } from "./client";
22
import React from "react";
33
import ReactDOM from "react-dom";
44
import { Layout } from "@reactpy/client/src/components";
5+
import { DjangoFormProps } from "./types";
6+
7+
/**
8+
* Interface used to bind a ReactPy node to React.
9+
*/
10+
export function bind(node) {
11+
return {
12+
create: (type, props, children) =>
13+
React.createElement(type, props, ...children),
14+
render: (element) => {
15+
ReactDOM.render(element, node);
16+
},
17+
unmount: () => ReactDOM.unmountComponentAtNode(node),
18+
};
19+
}
520

621
export function mountComponent(
722
mountElement: HTMLElement,
@@ -79,3 +94,34 @@ export function mountComponent(
7994
// Start rendering the component
8095
ReactDOM.render(<Layout client={client} />, client.mountElement);
8196
}
97+
98+
export function DjangoForm({
99+
onSubmitCallback,
100+
formId,
101+
}: DjangoFormProps): null {
102+
React.useEffect(() => {
103+
const form = document.getElementById(formId) as HTMLFormElement;
104+
105+
// Submission event function
106+
const onSubmitEvent = (event) => {
107+
event.preventDefault();
108+
const formData = new FormData(form);
109+
console.log(Object.fromEntries(formData));
110+
onSubmitCallback(Object.fromEntries(formData));
111+
};
112+
113+
// Bind the event listener
114+
if (form) {
115+
form.addEventListener("submit", onSubmitEvent);
116+
}
117+
118+
// Unbind the event listener when the component dismounts
119+
return () => {
120+
if (form) {
121+
form.removeEventListener("submit", onSubmitEvent);
122+
}
123+
};
124+
}, []);
125+
126+
return null;
127+
}

src/js/src/types.ts

+5
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,8 @@ export type ReactPyDjangoClientProps = {
1818
prerenderElement: HTMLElement | null;
1919
offlineElement: HTMLElement | null;
2020
};
21+
22+
export interface DjangoFormProps {
23+
onSubmitCallback: (data: Object) => void;
24+
formId: string;
25+
}

0 commit comments

Comments
 (0)