GithubHelp home page GithubHelp logo

ptzagk / react-use-form-state Goto Github PK

View Code? Open in Web Editor NEW

This project forked from wsmd/react-use-form-state

0.0 0.0 0.0 111 KB

๐Ÿ“„ A hook for managing forms and inputs state in React

Home Page: http://react-use-form-state.now.sh

License: MIT License

JavaScript 100.00%

react-use-form-state's Introduction


react-use-form-state

Motivation

Managing form state in React can be a bit unwieldy sometimes. There are plenty of great solutions already available that make managing forms state a breeze. However, many of those solutions are opinionated, packed with tons of features that may end up not being used, and/or requires shipping a few extra bytes!

Luckily, the recent introduction of React Hooks, and the ability to write custom ones have enabled new possibilities when it comes sharing state logic. Forms state is no expectation!

react-use-form-state is a small React Hook that attempts to simplify managing form state, using the native form input elements you are familiar with!

Getting Started

To get it started, add react-use-form-state to your project:

npm install --save react-use-form-state

Please note that react-use-form-state requires react@^16.7.0-alpha.0 as a peer dependency.

Examples

Basic Usage

import { useFormState } from 'react-use-form-state';

export default function SignUpForm() {
  const [formState, { text, email, password, radio }] = useFormState();
  return (
    <form onSubmit={() => console.log(formState)}>
      <input {...text('name')} />
      <input {...email('email')} required />
      <input {...password('password')} required minLength="8" />
      <input {...radio('plan', 'free')} />
      <input {...radio('plan', 'premium')} />
    </form>
  );
}

From the example above, as the user fills in the form, formState will look something like this:

{
  "values": {
    "name": "Mary Poppins",
    "email": "[email protected]",
    "password": "1234",
    "plan": "free",
  },
  "validity": {
    "name": true,
    "email": true,
    "password": false,
    "plan": true,
  },
  "touched": {
    "name": true,
    "email": true,
    "password": true,
    "plan": true,
  }
}

Initial State

useFormState takes an initial state object with keys matching the names of the inputs.

export default function RentCarForm() {
  const [formState, { checkbox, radio, select }] = useFormState({
    trip: 'roundtrip',
    type: ['sedan', 'suv', 'van'],
  });
  return (
    <form>
      <select {...select('trip')}>
        <option value="roundtrip">Same Drop-off</option>
        <option value="oneway">Different Drop-off</option>
      </select>
      <input {...checkbox('type', 'sedan')} />
      <input {...checkbox('type', 'suv')} />
      <input {...checkbox('type', 'van')} />
      <button>Submit</button>
    </form>
  );
}

Without Using a <form /> Element

react-use-form-state is not limited to actual forms. It can be used anywhere inputs are used.

function LoginForm({ onSubmit }) {
  const [formState, { email, password }] = useFormState();
  return (
    <div>
      <input {...email('email')} required />
      <input {...password('password')} required minLength="8" />
      <button onClick={() => onSubmit(formState)}>Login</button>
    </div>
  );
}

API

import { useFormState } from 'react-use-form-state';

function SignupForm({ onSubmit }) {
  const [formState, input] = useFormState(initialState);
  // ...
}

On initial render, useFormState takes an optional initial state object with keys as the name property of the form inputs, and values as the initial values of those inputs (similar to defaultValue/defaultChecked).

It returns an array of two items, the first is the form state, and the second an input types object.

Form State

The first item returned by useFormState.

const [formState, input] = useFormState()

An object describing the form state that updates during subsequent re-renders.

Form state consists of three nested objects:

  • values: an object holding the state of each input being rendered.
  • validity: an object indicating whether the value of each input is valid.
  • touched: an object indicating whether the input was touched (focused) by the user.
formState = {
  values: {
    [inputName: string]: string | string[],
  },
  validity: {
    [inputName: string]: boolean,
  },
  touched: {
    [inputName: string]: boolean,
  },
}

Input Types

The second item returned by useFormState.

const [formState, input] = useFormState()

An object with keys as input types. Each type is a function that returns the appropriate props that can be spread on the corresponding input.

The following types are currently supported:

Type and Usage State Shape
<select {...input.select(name: string) /> { [name: string]: string }
<input {...input.email(name: string) /> { [name: string]: string }
<input {...input.color(name: string) /> { [name: string]: string }
<input {...input.password(name: string) /> { [name: string]: string }
<input {...input.text(name: string) /> { [name: string]: string }
<input {...input.url(name: string) /> { [name: string]: string }
<input {...input.search(name: string) /> { [name: string]: string }
<input {...input.number(name: string) /> { [name: string]: string }
<input {...input.range(name: string) /> { [name: string]: string }
<input {...input.tel(name: string) /> { [name: string]: string }
<input {...input.radio(name: string, value: string) /> { [name: string]: string }
<input {...input.checkbox(name: string, value: string) /> { [name: string]: Array<string> }
<input {...input.date(name: string) /> { [name: string]: string }
<input {...input.month(name: string) /> { [name: string]: string }
<input {...input.week(name: string) /> { [name: string]: string }
<input {...input.time(name: string) /> { [name: string]: string }

License

MIT

react-use-form-state's People

Contributors

wsmd avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.