0.0.1 • Published 5 years ago

miniform v0.0.1

Weekly downloads
1
License
MIT
Repository
github
Last release
5 years ago

miniform

Build Status License: MIT

A simple way to manage forms with React and React Native. It has been designed to remove all of the state management we use to work with when creating forms in React.

Installation

$ yarn add miniform

In your code

The Field component

Let's imagine the following EmailInput component:

import React from "react";
import { Field } from "miniform";
import { emailRules } from "./emailRules";

export const EmailInput = () => (
  <Field name="email" rules={emailRules}>
    {({ changeValue, value, error, hasError }) => (
      <>
        <input
          placeholder="Enter an email"
          type="text"
          value={value}
          onChange={e => changeValue(e.target.value)}
        />
        <p>{hasError && error.first}</p>
      </>
    )}
  </Field>
);

Defining a set of rules with createRules and when

import { when, createRules } from "miniform";

export const emailRules = createRules([
  when(mail => !mail.includes("@"), () => "The mail should contain an @"),
  when(mail => !mail.includes(".com"), () => "The email should contain a .com")
]);

This creates a set of rules that can be passed inside a Field rules prop or by simply calling it:

const { first, all } = emailRules("invalid email");

console.log(first); // prints "The mail should contain an @"
console.log(all); // prints ["The mail should contain an @", "The email should contain a .com"]

A submit Field

import React from "react";
import { Field } from "form";

export const ValidationButton = ({ children, isLoading, onClick }) => (
  <Field name="validate">
    {({ fields }) => (
      <button
        onClick={onClick}
        disabled={!fields.email.value || fields.email.hasError}
      >
        {children}
      </button>
    )}
  </Field>
);

Every field is able to access all of the other fields using the fields props passed by the child render function.

Bring it all together

import { React } from "react";
import { Form } from "miniform";
import { EmailInput } from "./emailInput";
import { ValidationButton } from "./validation-button";

export const EmailForm = () => (
  <Form>
    <EmailInput />
    <ValidationButton />
  </Form>
);

And you're done :)