• Stars
    star
    914
  • Rank 49,973 (Top 1.0 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 5 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

⚡️ React Performance First Form Component

rc-field-form

React Performance First Form Component.

NPM version dumi build status Codecov npm download

Development

npm install
npm start
open http://localhost:8000

Feature

  • Support react.js and even react-native
  • Validate fields with async-validator

Install

rc-field-form

Usage

import Form, { Field } from 'rc-field-form';

const Input = ({ value = "", ...props }) => <input value={value} {...props} />;

const Demo = () => {
  return (
    <Form
      onFinish={(values) => {
        console.log("Finish:", values);
      }}
    >
      <Field name="username">
        <Input placeholder="Username" />
      </Field>
      <Field name="password">
        <Input placeholder="Password" />
      </Field>

      <button>Submit</button>
    </Form>
  );
};

export default Demo;

🔥 API

We use typescript to create the Type definition. You can view directly in IDE. But you can still check the type definition here.

Form

Prop Description Type Default
component Customize Form render component string | Component | false form
fields Control Form fields status. Only use when in Redux FieldData[] -
form Set form instance created by useForm FormInstance Form.useForm()
initialValues Initial value of Form Object -
name Config name with FormProvider string -
preserve Preserve value when field removed boolean false
validateMessages Set validate message template ValidateMessages -
onFieldsChange Trigger when any value of Field changed (changedFields, allFields) => void -
onFinish Trigger when form submit and success (values) => void -
onFinishFailed Trigger when form submit and failed ({ values, errorFields, outOfDate }) => void -
onValuesChange Trigger when any value of Field changed (changedValues, values) => void -

Field

Prop Description Type Default
dependencies Will re-render if dependencies changed NamePath[] -
getValueFromEvent Specify how to get value from event (..args: any[]) => any -
getValueProps Customize additional props with value. This prop will disable valuePropName (value) => any -
initialValue Field initial value any -
name Field name path NamePath -
normalize Normalize value before update (value, prevValue, prevValues) => any -
preserve Preserve value when field removed boolean false
rules Validate rules Rule[] -
shouldUpdate Check if Field should update boolean | (prevValues, nextValues) => boolean -
trigger Collect value update by event trigger string onChange
validateTrigger Config trigger point with rule validate string | string[] onChange
valuePropName Config value mapping prop with element string value

List

Prop Description Type Default
name List field name path NamePath[] -
children Render props for listing fields (fields: { name: NamePath }[], operations: ListOperations) => ReactNode -

useForm

Form component default create an form instance by Form.useForm. But you can create it and pass to Form also. This allow you to call some function on the form instance.

const Demo = () => {
  const [form] = Form.useForm();
  return <Form form={form} />;
};

For class component user, you can use ref to get form instance:

class Demo extends React.Component {
  setRef = form => {
    // Form instance here
  };

  render() {
    return <Form ref={this.setRef} />;
  }
}
Prop Description Type
getFieldValue Get field value by name path (name: NamePath) => any
getFieldsValue Get list of field values by name path list (nameList?: (NamePath[]) => any) | true
getFieldError Get field errors by name path (name: NamePath) => string[]
getFieldsError Get list of field errors by name path list (nameList?: NamePath[]) => FieldError[]
isFieldsTouched Check if list of fields are touched (nameList?: NamePath[], allTouched?: boolean) => boolean
isFieldTouched Check if a field is touched (name: NamePath) => boolean
isFieldValidating Check if a field is validating (name: NamePath) => boolean
resetFields Reset fields status (fields?: NamePath[]) => void
setFields Set fields status (fields: FieldData[]) => void
setFieldsValue Set fields value (values) => void
submit Trigger form submit () => void
validateFields Trigger fields to validate (nameList?: NamePath[], options?: ValidateOptions) => Promise

FormProvider

Prop Description Type Default
validateMessages Config global validateMessages template ValidateMessages -
onFormChange Trigger by named form fields change (name, { changedFields, forms }) => void -
onFormFinish Trigger by named form fields finish (name, { values, forms }) => void -

📋 Interface

NamePath

Type
string | number | (string | number)[]

FieldData

Prop Type
touched boolean
validating boolean
errors string[]
name string | number | (string | number)[]
value any

Rule

Prop Type
enum any[]
len number
max number
message string
min number
pattern RegExp
required boolean
transform (value) => any
type string
validator (rule, value, callback: (error?: string) => void, form) => Promise | void
whitespace boolean
validateTrigger string | string[]

validator

To keep sync with rc-form legacy usage of validator, we still provides callback to trigger validate finished. But in rc-field-form, we strongly recommend to return a Promise instead.

ListOperations

Prop Type
add (initValue: any) => void
remove (index: number) => void

ValidateMessages

Validate Messages provides a list of error template. You can ref here for fully default templates.

Prop Description
enum Rule enum prop
len Rule len prop
max Rule max prop
min Rule min prop
name Field name
pattern Rule pattern prop
type Rule type prop

Different with rc-form

rc-field-form is try to keep sync with rc-form in api level, but there still have something to change:

1. Field will not keep snyc with initialValues when un-touched

In rc-form, field value will get from initialValues if user not operate on it. It's a bug but user use as a feature which makes fixing will be a breaking change and we have to keep it. In Field Form, this bug will not exist anymore. If you want to change a field value, use setFieldsValue instead.

2. Remove Field will not clean up related value

We do lots of logic to clean up the value when Field removed before. But with user feedback, remove exist value increase the additional work to keep value back with conditional field.

3. Nest name use array instead of string

In rc-form, we support like user.name to be a name and convert value to { user: { name: 'Bamboo' } }. This makes '.' always be the route of variable, this makes developer have to do additional work if name is real contains a point like app.config.start to be app_config_start and parse back to point when submit.

Field Form will only trade ['user', 'name'] to be { user: { name: 'Bamboo' } }, and user.name to be { ['user.name']: 'Bamboo' }.

4. Remove validateFieldsAndScroll

Since findDomNode is marked as warning in StrictMode. It seems over control of Form component. We decide to remove validateFieldsAndScroll method and you should handle it with you own logic:

<Form>
  <Field name="username">
    <input ref={this.inputRef} />
  </Field>
</Form>

5. getFieldsError always return array

rc-form returns null when no error happen. This makes user have to do some additional code like:

(form.getFieldsError('fieldName') || []).forEach(() => {
  // Do something...
});

Now getFieldsError will return [] if no errors.

6. Remove callback with validateFields

Since ES8 is support async/await, that's no reason not to use it. Now you can easily handle your validate logic:

async function() {
  try {
    const values = await form.validateFields();
    console.log(values);
  } catch (errorList) {
    errorList.forEach(({ name, errors }) => {
      // Do something...
    });
  }
}

Notice: Now if your validator return an Error(message), not need to get error by e => e.message. FieldForm will handle this.

7. preserve is default to false

In rc-form you should use preserve to keep a value cause Form will auto remove a value from Field removed. Field Form will always keep the value in the Form whatever Field removed. But you can still use preserve=false to disable value keeping since 1.5.0.

8. setFields not trigger onFieldsChange and setFieldsValue not trigger onValuesChange

In rc-form, we hope to help user auto trigger change event by setting to make redux dispatch easier, but it's not good design since it makes code logic couping.

Additionally, user control update trigger onFieldsChange & onValuesChange event has potential dead loop risk.

More Repositories

1

slider

React Slider
JavaScript
2,962
star
2

form

React High Order Form Component(web & react-native)
JavaScript
1,799
star
3

calendar

React Calendar
JavaScript
1,681
star
4

table

React Table
TypeScript
1,183
star
5

tree

React Tree
TypeScript
1,113
star
6

tooltip

React Tooltip
TypeScript
896
star
7

select

React Select
TypeScript
854
star
8

upload

React Upload
TypeScript
766
star
9

progress

React Progress Bar
TypeScript
678
star
10

animate

anim react element easily
JavaScript
675
star
11

menu

React Menu
TypeScript
655
star
12

virtual-list

🧾 React Virtual List Component which worked with animation
TypeScript
645
star
13

pagination

React Pagination
TypeScript
629
star
14

util

Common Utils For React Component
TypeScript
627
star
15

tabs

React Tabs
TypeScript
540
star
16

queue-anim

Animate React Component in queue
TypeScript
476
star
17

time-picker

React TimePicker
JavaScript
463
star
18

dialog

React Dialog
TypeScript
424
star
19

color-picker

React ColorPicker
TypeScript
422
star
20

m-date-picker

React Mobile DatePicker(web & react-native)
TypeScript
400
star
21

react-component.github.io

docs and site of react-component
HTML
378
star
22

drawer

React Drawer
TypeScript
372
star
23

tween-one

Animate One React Element
TypeScript
370
star
24

notification

React Notification
TypeScript
364
star
25

trigger

Abstract React Trigger
TypeScript
345
star
26

collapse

React Collapse / Accordion
TypeScript
319
star
27

steps

React Steps
TypeScript
311
star
28

scroll-anim

Animate Scroll React Component
JavaScript
301
star
29

input-number

React Input Number
TypeScript
296
star
30

tree-select

React Tree Select
TypeScript
287
star
31

picker

📅 All Date Pickers you need.
TypeScript
265
star
32

m-picker

React Mobile Picker(web & react-native)
TypeScript
247
star
33

swipeout

React Swipeout(web & react-native)
TypeScript
213
star
34

rc-tools

Tools For React Component
JavaScript
205
star
35

cascader

cascade select in one box
TypeScript
198
star
36

switch

React Switch
JavaScript
187
star
37

image

🖼 React Image Component
TypeScript
185
star
38

banner-anim

Animate Banner React Component
JavaScript
170
star
39

m-pull-to-refresh

React Mobile Pull To Refresh
TypeScript
164
star
40

dropdown

React Dropdown
TypeScript
163
star
41

texty

React Text Animate
TypeScript
154
star
42

resize-observer

👓 Resize observer for React
JavaScript
153
star
43

m-tabs

React Mobile Tabs Component (web & react-native)
TypeScript
139
star
44

checkbox

React Checkbox
TypeScript
130
star
45

motion

⛷ CSS Animation for React
TypeScript
120
star
46

gesture

Support gesture for react component.
TypeScript
103
star
47

rate

React Rate
JavaScript
91
star
48

footer

🐾 Pretty Footer react component used in ant.design
JavaScript
87
star
49

form-validation

This project is deprecated, you can try https://github.com/react-component/form
JavaScript
86
star
50

m-list-view

ReactNative ListView Web Port
JavaScript
85
star
51

align

Abstract React Align
TypeScript
81
star
52

mentions

React Mentions
TypeScript
67
star
53

rn-packager

Standalone ReactNative Packager
JavaScript
66
star
54

generator-rc

yeoman generator for react component
JavaScript
58
star
55

editor-core

a draft-js based editor
TypeScript
56
star
56

m-drawer

React Drawer
JavaScript
54
star
57

cropping

image cropping
TypeScript
54
star
58

editor-mention

React Mention
JavaScript
53
star
59

m-cascader

React Mobile Cascader Component(web and react-native)
TypeScript
51
star
60

m-dialog

React Mobile Dialog(web & react-native)
TypeScript
45
star
61

spider

React Tree Diagrams
JavaScript
44
star
62

overflow

📦 Auto collapse box util component
TypeScript
42
star
63

css-transition-group

standalone CSSTransitionGroup for React.addons.CSSTransitionGroup
JavaScript
38
star
64

m-calendar

React Mobile Calendar Component (web)
TypeScript
36
star
65

m-feedback

:active pseudo-class with react for mobile
TypeScript
36
star
66

input

React Input Component
TypeScript
35
star
67

tour

TypeScript
30
star
68

pager

React Pager
JavaScript
26
star
69

m-notification

JavaScript
23
star
70

dropzone

React Dropzone
JavaScript
23
star
71

textarea

React Textarea
TypeScript
22
star
72

radio

[DEPRECATED] React Radio
CSS
19
star
73

m-input-number

input-number mobile ui component for react (web & react-native)
TypeScript
17
star
74

portal

TypeScript
16
star
75

touchable

React Touchable Component
TypeScript
16
star
76

rc-server

This project is deprecated, use rc-tools run server
JavaScript
15
star
77

gulp-jsx2example

Compile JSX file to HTML (react demo)
JavaScript
13
star
78

cascade-select

React CascadeSelect
JavaScript
13
star
79

icon-anim

Icon cutover or morph animate React Element
JavaScript
12
star
80

m-select-list

React Mobile Select List Component
JavaScript
12
star
81

segmented

React Segmented Controls
TypeScript
12
star
82

rc-test

test react component
JavaScript
11
star
83

mobile

ant design mobile components
TypeScript
10
star
84

m-tooltip

React Tooltip for mobile
TypeScript
8
star
85

context

TypeScript
7
star
86

rn-tools

tools for react-native
JavaScript
7
star
87

rn-core

Standalone ReactNative Framework
Objective-C
6
star
88

m-trigger

React Trigger Component for mobile
JavaScript
6
star
89

record

Record audio from microphone
JavaScript
5
star
90

.github

5
star
91

RNPlayground

react-native playground container
Objective-C
5
star
92

mutate-observer

TypeScript
5
star
93

editor-plugin-emoji

HTML
4
star
94

m-steps

React Steps for mobile
CSS
4
star
95

editor-plugin-basic-style

TypeScript
3
star
96

mini-decimal

TypeScript
3
star
97

editor-utils

editor utilities
TypeScript
2
star
98

father-plugin

father plugin for all react-component project
TypeScript
1
star
99

qrcode

TypeScript
1
star
100

editor-plugin-image

TypeScript
1
star