IT, 筆記

Learn react-jsonschema-form (1)

This post is the continuation from the previous post - Learn ReactJS 17 + react-jsonschema-form + typescript

The previous exercise is based on the usage section in the react-jsonschema-form project documentation. That example declares the schema in the code and initializes the component with that hard-coded schema. Is it possible to place the schema JSON file in the public directory and load it as needed?

Move out the schema

create a folder assets under public directory and create the schema file ./public/assets/testschema.json with the following content:

{
  "title": "Todo",
  "type": "object",
  "required": ["title"],
  "properties": {
    "title": { "type": "string", "title": "Title", "default": "A new task" },
    "done": { "type": "boolean", "title": "Done?", "default": false }
  }
}

Load the schema then Set the form schema

In order to load the json file, I use fetch(), the following code will read the file and cast the json object to JSONSchema type:

fetch("/assets/testschema.json")
  .then((r) => r.json())
  .then((data) => {
    let schema = data as JSONSchema7;
    // Load or update the form schema
  });

Make the component properties to handle the form schema

Expose the <Form> schema property in <MyFrom>:

function MyFrom(props: any) {
  return (
    <Form
      schema={props.schema}
      onChange={log("changed")}
      onSubmit={log("submitted")}
      onError={log("errors")}
    />
  );
}

Put it together

import React from "react";
import ReactDOM from "react-dom";
import Form from "@rjsf/bootstrap-4";
import { JSONSchema7 } from "json-schema";

import "./index.scss";

const jsonSchemaFile = "/assets/testschema.json";

const log = (type: string) => console.log.bind(console, type);

function MyFrom(props: any) {
  return (
    <Form
      schema={props.schema}
      onChange={log("changed")}
      onSubmit={log("submitted")}
      onError={log("errors")}
    />
  );
}

fetch(jsonSchemaFile)
  .then((r) => r.json())
  .then((data) => {
    let schema = data as JSONSchema7;
    ReactDOM.render(
      <MyFrom schema={schema} />,
      document.querySelector("#root")
    );
  });

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *