0.1.3 • Published 2 years ago

react-hook-form-builder v0.1.3

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

React hook form builder

Light weight schema Form builder for react-hook-form.

NPM

This package takes your schema and builds the form based on that using your own components.

Demo

The working react example is here.

Installation

npm i react-hook-form react-hook-form-builder

or with yarn

yarn add react-hook-form react-hook-form-builder

Usage

  1. define your form elements:
export const elements = [
  { key: "BasicInput", element: BasicInput },
  { key: "Button", element: Button },
];
  1. wrap your root app with <FormBuilderProvider /> and define your elements:
import { FormBuilderProvider } from "react-hook-form-builder";
import { elements } from "../constants/elements.ts";

export default function App() {
  return (
    <div className="App">
      <FormBuilderProvider elements={elements}>
        ...
        {" your app ..."}
      </FormBuilderProvider>
    </div>
  );
}
  1. define your schema:
const schema = [
  {
    key: "firstName",
    elementType: "BasicInput",
    defaultValue: "john",
    props: {
      placeholder: "First Name",
    },
  },
  {
    key: "lastName",
    elementType: "BasicInput",
    props: {
      placeholder: "Last Name",
    },
  },
  {
    key: "submit",
    elementType: "Button",
    ignoreController: true,
    props: ({ formState: { isDirty } }: any) => ({
      type: "submit",
      label: isDirty ? "Save" : "Submit",
    }),
  },
];
  1. in your desire form, just render your form using <FormBuilder /> and pass your schema & react-hook-form methods:
import { FormBuilder } from "react-hook-form-builder";
import { useForm } from "react-hook-form";
import { schema } from "../constants/contactUsPageSchema.ts";

export default function ContactUsPage() {
  const methods = useForm();
  const onSubmit = (data: any) => console.log(data);

  return (
    <div className="contact-us-page">
      <FormBuilder methods={methods} schema={schema} onSubmit={onSubmit} />
    </div>
  );
}

Documents

schema props

TypeTypeDescription
keystringunique key for each form element.
elementTypestringDefine element type
propsanyProps passing to element component.
rulesHTML standard for form validation
defaultValueany
ignoreControllerbooleanignore wrapping element inside <Controller />.

Example element

import React, { InputHTMLAttributes, ReactElement } from "react";

type IBasicInput = (props: InputHTMLAttributes<HTMLInputElement>) => ReactElement;

const BasicInput: IBasicInput = (props) => {
  return <input {...props} />;
};

export default BasicInput;