GithubHelp home page GithubHelp logo

hhy5277 / unform Goto Github PK

View Code? Open in Web Editor NEW

This project forked from unform/unform

0.0 1.0 0.0 676 KB

ReactJS form library to create uncontrolled form structures with nested fields, validations and much more!

License: MIT License

JavaScript 14.30% TypeScript 84.50% HTML 1.20%

unform's Introduction

NPM Build Status

Overview

Unform is a performance focused library that helps you creating beautiful forms in React with the power of uncontrolled components performance and React Hooks.

Main advantages

  • Beautiful syntax;
  • React Hooks ๐Ÿ˜;
  • Performance focused;
  • Use of uncontrolled components;
  • Integration with pickers, dropdowns and other libraries;

Why not Formik, Redux Form or another library?

Formik/Redux Form has a really great syntax while it has a really poor support to uncontrolled components and deep nested data structures. With unform it's easy to create forms with complex relationships without losing performance.

Roadmap

  • Native checkbox/radio support;
  • Styled components support;
  • React Native support (should we?);
  • Better docs;

Installation

Just add unform to your project:

yarn add @rocketseat/unform

Table of contents

Guides

Basics

import React from "react";
import { Form, Input } from "@rocketseat/unform";

function App() {
  function handleSubmit(data) {
    console.log(data);

    /**
     * {
     *   email: '[email protected]',
     *   password: "123456"
     * }
     */
  };

  return (
    <Form onSubmit={handleSubmit}>
      <Input name="email" />
      <Input name="password" type="password" />

      <button type="submit">Sign in</button>
    </Form>
  );
}

Nested fields

import React from "react";
import { Form, Input, Scope } from "@rocketseat/unform";

function App() {
  function handleSubmit(data) {
    console.log(data);

    /**
     * {
     *   name: 'Diego',
     *   address: { street: "Name of street", number: 123 }
     * }
     */
  };

  return (
    <Form onSubmit={handleSubmit}>
      <Input name="name" />

      <Scope path="address">
        <Input name="street" />
        <Input name="number" />
      </Scope>

      <button type="submit">Save</button>
    </Form>
  );
}

Initial data

import React from "react";
import { Form, Input, Scope } from "@rocketseat/unform";

function App() {
  const initialData = {
    name: 'John Doe',
    address: {
      street: 'Sample Avenue',
    },
  }

  function handleSubmit(data) {};

  return (
    <Form onSubmit={handleSubmit} initialData={initialData}>
      <Input name="name" />

      <Scope path="address">
        <Input name="street" />
        <Input name="number" />
      </Scope>

      <button type="submit">Save</button>
    </Form>
  );
}

Validation

import React from "react";
import { Form, Input } from "@rocketseat/unform";
import * as Yup from 'yup';

const schema = Yup.object().shape({
  email: Yup.string()
    .email('Custom invalid email message')
    .required('Custom required message'),
  password: Yup.string().min(4).required(),
})

function App() {
  function handleSubmit(data) {};

  return (
    <Form schema={schema} onSubmit={handleSubmit}>
      <Input name="email" />
      <Input name="password" type="password" />

      <button type="submit">Save</button>
    </Form>
  );
}

Manipulate data

import React, { useState } from "react";
import { Form, Input } from "@rocketseat/unform";
import * as Yup from 'yup';

const schema = Yup.object().shape({
  name: Yup.string().required(),
  email: Yup.string().email().required(),
  password: Yup.string().when('$updatePassword', {
    is: true,
    then: Yup.string().min(4).required(),
    otherwise: Yup.string().strip(true)
  }),
})

function App() {
  const [updatePassword, setUpdatePassword] = useState(false);

  const initialData = {
    name: 'John Doe',
    email: '[email protected]',
  }

  function handleSubmit(data) {};

  return (
    <Form
      schema={schema}
      initialData={initialData}
      context={{ updatePassword }}
      onSubmit={handleSubmit}
    >
      <Input name="name" />
      <Input name="email" />

      <input
        type="checkbox"
        name="Update Password"
        checked={updatePassword}
        onChange={e => setUpdatePassword(e.target.checked)}
      />

      <Input name="password" type="password" />

      <button type="submit">Save</button>
    </Form>
  );
}

Custom elements

Sometimes we need to use third-party component in our forms. But don't you worry, Unform has your back! You can do that via useField which provides all the resources you need to use your component with Unform.

Below are some examples with react-select and react-datepicker.

React select

import React, { useState } from "react";
import { Form, useField } from "@rocketseat/unform";
import Select from 'react-select';

/* You can't use your component directly, you have to wrap it
around another component, or you won't be able to use useField properly */
function ReactSelect({ name, options, multiple }) {
  const { fieldName, registerField, defaultValue, error } = useField(name);
  const [value, setValue] = useState(defaultValue);

  function getValue() {
    if (!multiple) {
      return value;
    }

    return value.reduce((res, item) => {
      res.push(item.value);
      return res;
    }, []);
  }

  return (
    <>
      <Select
        name="techs"
        options={options}
        isMulti={multiple}
        value={value}
        onChange={setValue}
        ref={() => registerField({ name: fieldName, ref: getValue })}
      />

      {error && <span>{error}</span>}
    </>
  )
}

function App() {
  const techs = [
    { value: "react", label: "ReactJS" },
    { value: "node", label: "NodeJS" },
    { value: "rn", label: "React Native" }
  ];

  const colors = [
    { value: "red", label: "Red" },
    { value: "green", label: "Green" },
    { value: "blue", label: "Blue" }
  ]

  const initialData = {
    color: { value: 'green', label: 'Green' },
    techs: [
      {
        value: 'react', label: 'ReactJS'
      },
    ],
  }

  function handleSubmit(data) {};

  return (
    <Form initialData={initialData} onSubmit={handleSubmit}>
      <ReactSelect options={colors} name="color" />

      <br />

      <ReactSelect options={techs} name="techs" multiple />

      <button type="submit">Save</button>
    </Form>
  );
}

React datepicker

import React, { useState } from "react";
import { Form, useField } from "@rocketseat/unform";
import DatePicker from 'react-datepicker';

import 'react-datepicker/dist/react-datepicker.css';

/* You can't use your component directly, you have to wrap it
around another component, or you won't be able to use useField properly */
function ReactDate({ name }) {
  const { fieldName, registerField, defaultValue, error } = useField(name);
  const [value, setValue] = useState(defaultValue);

  function getValue() {
    return value;
  }

  return (
    <>
      <DatePicker
        selected={value}
        onChange={setValue}
        ref={() => registerField({ name: fieldName, ref: getValue })}
      />
      {error && <span>{error}</span>}
    </>
  )
}

function App() {
  function handleSubmit(data) {};

  return (
    <Form onSubmit={handleSubmit}>
      <ReactDate name="birthday" />

      <button type="submit">Save</button>
    </Form>
  );
}

Contribute

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

License

MIT ยฉ Rocketseat

unform's People

Contributors

diego3g avatar eliezercm avatar higoribeiro avatar jpdemagalhaes avatar pellizzetti avatar victorsalesdev avatar

Watchers

 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.