-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReactJs18.react.tsx
72 lines (60 loc) · 1.75 KB
/
ReactJs18.react.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/** @jsxImportSource react */
// TODO: Extract to a dedicated React wrapper component?
// NOTE: React 18 doesn't have any declarative way to communicate with a
// Custom Element API. It might change with React 19, bringing partial,
// or maybe full support.
import { useState, useRef, useEffect } from 'react';
import '@jsfe/shoelace';
import type { FromSchema, JSONSchema7, Jsf } from '@jsfe/shoelace';
// -----------------------------------------------------------------------------
const mySchema = {
type: 'object',
properties: {
foo: {
type: 'string',
},
bar: {
type: 'boolean',
},
},
} as const satisfies JSONSchema7;
type MyData = FromSchema<typeof mySchema>;
function assertValidData(data: unknown): data is MyData {
// Use your AJV or other schema checker here, if you need thorough validation
// ...
return true;
}
export default function ReactJs18() {
const [dataInReact, setDataInReact] = useState<MyData>({
foo: 'hello',
});
const formRef = useRef<Jsf>();
useEffect(() => {
const form = formRef.current!;
form.data = dataInReact;
form.schema = /* Type-casted as JSONSchema7 */ mySchema;
form.uiSchema = {
/* Type-casted as UiSchema */
bar: {
'ui:widget': 'switch',
},
};
form.dataChangeCallback = (newData) => {
console.log({ 'Data from React 18': newData });
if (assertValidData(newData)) setDataInReact(newData);
else console.error('Invalid data!');
};
form.submitCallback = (newData, valid) => {
console.log({ 'Submitted from React 18!': newData, valid });
if (assertValidData(newData)) {
// Do stuff...
}
};
}, []);
return (
<article id="react">
<jsf-shoelace ref={formRef}></jsf-shoelace>
<pre>{JSON.stringify({ data: dataInReact }, null, 2)}</pre>
</article>
);
}