@@ -2,6 +2,21 @@ import { ReactPyDjangoClient } from "./client";
22import React from "react" ;
33import ReactDOM from "react-dom" ;
44import { 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
621export 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+ }
0 commit comments