1
- import { DjangoFormProps , HttpRequestProps } from "./types" ;
2
- import React from "react " ;
3
- import ReactDOM from "react-dom " ;
1
+ import type { DjangoFormProps , HttpRequestProps } from "./types" ;
2
+ import { useEffect } from "preact/hooks " ;
3
+ import { type ComponentChildren , render , createElement } from "preact " ;
4
4
/**
5
5
* Interface used to bind a ReactPy node to React.
6
6
*/
7
- export function bind ( node ) {
7
+ export function bind ( node : HTMLElement | Element | Node ) {
8
8
return {
9
- create : ( type , props , children ) =>
10
- React . createElement ( type , props , ...children ) ,
11
- render : ( element ) => {
12
- ReactDOM . render ( element , node ) ;
9
+ create : (
10
+ type : string ,
11
+ props : Record < string , unknown > ,
12
+ children : ComponentChildren [ ] ,
13
+ ) => createElement ( type , props , ...children ) ,
14
+ render : ( element : HTMLElement | Element | Node ) => {
15
+ render ( element , node ) ;
13
16
} ,
14
- unmount : ( ) => ReactDOM . unmountComponentAtNode ( node ) ,
17
+ unmount : ( ) => render ( null , node ) ,
15
18
} ;
16
19
}
17
20
18
21
export function DjangoForm ( {
19
22
onSubmitCallback,
20
23
formId,
21
24
} : DjangoFormProps ) : null {
22
- React . useEffect ( ( ) => {
25
+ useEffect ( ( ) => {
23
26
const form = document . getElementById ( formId ) as HTMLFormElement ;
24
27
25
28
// Submission event function
26
- const onSubmitEvent = ( event ) => {
29
+ const onSubmitEvent = ( event : Event ) => {
27
30
event . preventDefault ( ) ;
28
31
const formData = new FormData ( form ) ;
29
32
30
33
// Convert the FormData object to a plain object by iterating through it
31
34
// If duplicate keys are present, convert the value into an array of values
32
35
const entries = formData . entries ( ) ;
33
36
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 ) ;
37
+ const formDataObject = formDataArray . reduce < Record < string , unknown > > (
38
+ ( acc , [ key , value ] ) => {
39
+ if ( acc [ key ] ) {
40
+ if ( Array . isArray ( acc [ key ] ) ) {
41
+ acc [ key ] . push ( value ) ;
42
+ } else {
43
+ acc [ key ] = [ acc [ key ] , value ] ;
44
+ }
38
45
} else {
39
- acc [ key ] = [ acc [ key ] , value ] ;
46
+ acc [ key ] = value ;
40
47
}
41
- } else {
42
- acc [ key ] = value ;
43
- }
44
- return acc ;
45
- } , { } ) ;
48
+ return acc ;
49
+ } ,
50
+ { } ,
51
+ ) ;
46
52
47
53
onSubmitCallback ( formDataObject ) ;
48
54
} ;
@@ -64,7 +70,7 @@ export function DjangoForm({
64
70
}
65
71
66
72
export function HttpRequest ( { method, url, body, callback } : HttpRequestProps ) {
67
- React . useEffect ( ( ) => {
73
+ useEffect ( ( ) => {
68
74
fetch ( url , {
69
75
method : method ,
70
76
body : body ,
0 commit comments