npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@capdilla/react-d-form

v3.1.0

Published

React, React Native form builder

Downloads

46

Readme

DForm

React Form Builder

build easy and powerfull forms with this library

Features

  • ReactJs and React Native support
  • Strong Validation
  • Write your Form Componets once use any times
  • Easy to handle state
  • is not needed Yup, Superstruct, Joi

Table of content

How To use

Installation

npm i @capdilla/react-d-form

Basic Use

import { ReactDForm } from "@capdilla/react-d-form";

const App = () => (
  <ReactDForm
    defaultState={{ name: "John" }}
    onFormChange={formValues => {
      if (formValues.validation.ISFORMVALID) {
        console.log("The form is valid");
      } else {
        console.log("Form is not valid");
      }

      console.log(formValues.data.email);
      console.log(formValues.data.name);
      console.log(formValues.data.surname);
    }}
    fields={[
      {
        fields: [
          {
            name: "name",
            type: "Input",
            validation: { required: true }
          },
          {
            name: "surname",
            type: "Input",
            validation: { required: true }
          }
        ]
      },
      {
        fields: [
          {
            name: "email",
            type: "Input",
            props: { type: "email" }
          }
        ]
      }
    ]}
  />
);

this example will create a form with two inputs in a row and one input in a second row, the input with the name email will going to be a <input type=email/>

Create Custom Form

this example use reactstrap but you can use any css library

1st Step create a new component

import React from "react";
import Core, { GetComponent } from "@capdilla/react-d-form";
import { Row } from "reactstrap";

import FormComponents from "../FormComponents";

const Elm = props => GetComponent(FormComponents, props);

export default class Form extends Core {
  render() {
    return (
      <div className="av-tooltip tooltip-label-right">
        <Row>
          {this.rows(rows => (
            <>
              {this.fieldFn(rows, (r, key) => (
                <Elm key={key} {...r} />
              ))}
            </>
          ))}
        </Row>
      </div>
    );
  }
}

Is mandatory to implement this.rows and this.fieldFn

2nd Step create yours custom components

this going to be the FormComponents file

import React, { useMemo } from "react";

import { withError } from "@capdilla/react-d-form";
import { FormGroup, Label, Col } from "reactstrap";
import Select from "react-select";

const Components = {
  Input: withError(
    ({ name, label, onChange, onBlur, props, value, placeholder, error }) => {
      return (
        <Col>
          <FormGroup className="form-group has-float-label">
            <Label>{label}</Label>
            <input
              className="form-control"
              value={value}
              placeholder={placeholder}
              name={name}
              onChange={e => onChange(e.target.value)}
              onBlur={e => onBlur(e.target.value)}
              {...props}
            />
            {error && (
              <div className="invalid-feedback d-block">{error.content}</div>
            )}
          </FormGroup>
        </Col>
      );
    }
  ),
  Select: withError(
    ({
      name,
      label,
      onChange,
      onBlur,
      props,
      value,
      placeholder,
      error,
      options
    }) => {
      const indexedValues = useMemo(
        () =>
          options.reduce(
            (acc, option) => ({ ...acc, [option.value]: option }),
            {}
          ),
        [options]
      );

      return (
        <Col>
          <FormGroup className="form-group has-float-label">
            <Label>{label}</Label>
            <Select
              className={`react-select `}
              classNamePrefix="react-select"
              options={options}
              onChange={e => onChange(e.value)}
              value={indexedValues[value]}
            />
            {error && (
              <div className="invalid-feedback d-block">{error.content}</div>
            )}
          </FormGroup>
        </Col>
      );
    }
  )
};

export default Components;

3rd Step (optional) create form.d.ts

The name of this file should be the same name of the file created in the 1st STEP

This step is optional but it going to improve the TypeScript support for your Form component (1st STEP)

/// <reference types="react" />
import Core from "@capdilla/react-d-form";
export default class Form<T> extends Core<T> {
  render(): JSX.Element;
}

4th Step use your custom Form component

import Form from "../components/Form";

const App = () => (
  <Form
    fields={[
      {
        fields: [
          {
            name: "name",
            type: "Input",
            validation: { required: true }
          }
        ]
      }
    ]}
  />
);

Add Typescript Support

1st Step Add Generic type to Form Component

this it the same

export default class Form<T> extends Core<T> {
  //render implementation here
}

2nd Step add typescript support to FormComponents

import { FormComponent } from "@capdilla/react-d-form";

interface Iinput extends FormComponent {
  onBlur: (value: any) => any;
}

interface ISelect extends FormComponent {
  options: {
    label: string,
    value: string
  }[];
}

const Components = {
  Input: withError(
    ({
      name,
      label,
      onChange,
      onBlur,
      props,
      value,
      placeholder,
      error
    }: Iinput) => {
      return (
        <Col>
          <FormGroup className="form-group has-float-label">
            <Label>{label}</Label>
            <input
              className="form-control"
              value={value}
              placeholder={placeholder}
              name={name}
              onChange={e => onChange(e.target.value)}
              onBlur={e => onBlur(e.target.value)}
              {...props}
            />
            {error && (
              <div className="invalid-feedback d-block">{error.content}</div>
            )}
          </FormGroup>
        </Col>
      );
    }
  ),
  Select: withError(
    ({
      name,
      label,
      onChange,
      onBlur,
      props,
      value,
      placeholder,
      error,
      options
    }: ISelect) => {
      const indexedValues = useMemo(
        () =>
          options.reduce(
            (acc, option) => ({ ...acc, [option.value]: option }),
            {}
          ),
        [options]
      );

      return (
        <Col>
          <FormGroup className="form-group has-float-label">
            <Label>{label}</Label>
            <Select
              className={`react-select `}
              classNamePrefix="react-select"
              options={options}
              onChange={e => onChange(e.value)}
              value={indexedValues[value]}
            />
            {error && (
              <div className="invalid-feedback d-block">{error.content}</div>
            )}
          </FormGroup>
        </Col>
      );
    }
  )
};

export default Components;

Validate Form

Required field

<Form
  fields={[
    {
      fields: [
        {
          name: "name",
          type: "Input",
          validation: { required: true }
        }
      ]
    }
  ]}
/>

Custom error message

errorMessage is not requied by default the Form component will return FIELD_REQUIRED

<Form
  fields={[
    {
      fields: [
        {
          name: "name",
          type: "Input",
          validation: {
            required: true,
            errorMessage: "This field cannot be empty"
          }
        }
      ]
    }
  ]}
/>

Validate by regex

in this example will validate if the input is an email

<Form
  fields={[
    {
      fields: [
        {
          name: "email",
          type: "Input",
          validation: {
            regexType: "email",
            errorMessage: "is not an email"
          }
        }
      ]
    }
  ]}
/>

others regex availables

| Regex type | description | | ---------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------: | | email | validate an email | | phone | validate an phone | | number | validate if is a number | | double | validate if is a number with decimals | | password | validate password with next requisits: must contain at least eight characters, at least one number and both lower and uppercase letters and special characters |

Validate by custom validation

<Form
  fields={[
    {
      fields: [
        {
          name: "email",
          type: "Input",
          validation: {
            custom: values => ({
              valid: values.email === "[email protected]",
              errorMessage: "Email must be [email protected]"
            })
          }
        }
      ]
    }
  ]}
/>

Handle state and values

Get Async values

const TestForm = () => {
  const [formData, setFormData] = useState({});

  const getData = () => {
    setTimeout(() => {
      setFormData({ formData: { name: "Jonh", surname: "Doe", age: 20 } });
    }, 2000);
  };

  useEffect(() => {
    getData();
  }, []);

  return (
    <Form
      defaultState={formData}
      onFormChange={data => {
        setFormData(data);
      }}
      fields={[
        {
          fields: [
            {
              name: "name",
              type: "Input"
            },
            {
              name: "surname",
              type: "Input"
            }
          ]
        },
        {
          fields: [
            {
              name: "age",
              type: "Input"
            }
          ]
        }
      ]}
    />
  );
};

For more examples see /stories folder