@@ -2,6 +2,21 @@ import { ReactPyDjangoClient } from "./client";
2
2
import React from "react" ;
3
3
import ReactDOM from "react-dom" ;
4
4
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
+ }
5
20
6
21
export function mountComponent (
7
22
mountElement : HTMLElement ,
@@ -79,3 +94,34 @@ export function mountComponent(
79
94
// Start rendering the component
80
95
ReactDOM . render ( < Layout client = { client } /> , client . mountElement ) ;
81
96
}
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
+ }
0 commit comments