• Stars
    star
    1,799
  • Rank 25,827 (Top 0.6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 9 years ago
  • Updated almost 3 years ago

Reviews

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

Repository Details

React High Order Form Component(web & react-native)

rc-form

React High Order Form Component.

NPM version build status Test coverage gemnasium deps node version npm download Code Quality: Javascript Total alerts

Development

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

Feature

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

Install

rc-form

Usage

import { createForm, formShape } from 'rc-form';

class Form extends React.Component {
  static propTypes = {
    form: formShape,
  };

  submit = () => {
    this.props.form.validateFields((error, value) => {
      console.log(error, value);
    });
  }

  render() {
    let errors;
    const { getFieldProps, getFieldError } = this.props.form;
    return (
      <div>
        <input {...getFieldProps('normal')}/>
        <input {...getFieldProps('required', {
          onChange(){}, // have to write original onChange here if you need
          rules: [{required: true}],
        })}/>
        {(errors = getFieldError('required')) ? errors.join(',') : null}
        <button onClick={this.submit}>submit</button>
      </div>
    );
  }
}

export createForm()(Form);

Use with React Native

Expo preview

avatar

View the source code

Or a quicker version:

import { createForm } from 'rc-form';

class Form extends React.Component {
  componentWillMount() {
    this.requiredDecorator = this.props.form.getFieldDecorator('required', {
      rules: [{required: true}],
    });
  }

  submit = () => {
    this.props.form.validateFields((error, value) => {
      console.log(error, value);
    });
  }

  render() {
    let errors;
    const { getFieldError } = this.props.form;
    return (
      <div>
        {this.requiredDecorator(
          <input
            onChange={
              // can still write your own onChange
            }
          />
        )}
        {(errors = getFieldError('required')) ? errors.join(',') : null}
        <button onClick={this.submit}>submit</button>
      </div>
    );
  }
}

export createForm()(Form);

createForm(option: Object) => (WrappedComponent: React.Component) => React.Component

Option Description Type Default
option.validateMessages Preseted messages of async-validator Object {}
option.onFieldsChange Called when field changed, you can dispatch fields to redux store. (props, changed, all): void NOOP
option.onValuesChange Called when value changed. (props, changed, all): void NOOP
option.mapProps Get new props transferred to WrappedComponent. (props): Object props => props
option.mapPropsToFields Convert value from props to fields. Used for read fields from redux store. (props): Object NOOP
option.fieldNameProp Where to store the name argument of getFieldProps. String -
option.fieldMetaProp Where to store the meta data of getFieldProps. String -
option.fieldDataProp Where to store the field data String -
option.withRef(deprecated) Maintain an ref for wrapped component instance, use refs.wrappedComponent to access. boolean false

Note: use wrappedComponentRef instead of withRef after [email protected]

class Form extends React.Component { ... }

// deprecated
const EnhancedForm = createForm({ withRef: true })(Form);
<EnhancedForm ref="form" />
this.refs.form.refs.wrappedComponent // => The instance of Form

// Recommended
const EnhancedForm = createForm()(Form);
<EnhancedForm wrappedComponentRef={(inst) => this.formRef = inst} />
this.formRef // => The instance of Form

(WrappedComponent: React.Component) => React.Component

The returned function of createForm(). It will pass an object as prop form with the following members to WrappedComponent:

getFieldProps(name, option): Object { [valuePropName], [trigger], [validateTrigger] }

Will create props which can be set on a input/InputComponent which support value and onChange interface.

After set, this will create a binding with this input.

<form>
  <input {...getFieldProps('name', { ...options })} />
</form>

name: String

This input's unique name.

option: Object

Option Description Type Default
option.valuePropName Prop name of component's value field, eg: checkbox should be set to checked ... String 'value'
option.getValueProps Get the component props according to field value. (value): Object (value) => ({ value })
option.getValueFromEvent Specify how to get value from event. (e): any See below
option.initialValue Initial value of current component. any -
option.normalize Return normalized value. (value, prev, all): Object -
option.trigger Event which is listened to collect form data. String 'onChange'
option.validateTrigger Event which is listened to validate. Set to falsy to only validate when call props.validateFields. String String[]
option.rules Validator rules. see: async-validator Object[] -
option.validateFirst Whether stop validate on first rule of error for this field. boolean false
option.validate Object[] -
option.validate[n].trigger Event which is listened to validate. Set to falsy to only validate when call props.validateFields. String String[]
option.validate[n].rules Validator rules. see: async-validator Object[] -
option.hidden Ignore current field while validating or gettting fields boolean false
option.preserve Whether to preserve the value. That will remain the value when the field be unmounted and be mounted again boolean false
Default value of getValueFromEvent
function defaultGetValueFromEvent(e) {
  if (!e || !e.target) {
    return e;
  }
  const { target } = e;
  return target.type === 'checkbox' ? target.checked : target.value;
}
Tips
{
  validateTrigger: 'onBlur',
  rules: [{required: true}],
}
// is the shorthand of
{
  validate: [{
    trigger: 'onBlur',
    rules: [{required: true}],
  }],
}

getFieldDecorator(name:String, option: Object) => (React.Node) => React.Node

Similar to getFieldProps, but add some helper warnings and you can write onXX directly inside React.Node props:

<form>
  {getFieldDecorator('name', otherOptions)(<input />)}
</form>

getFieldsValue([fieldNames: String[]])

Get fields value by fieldNames.

getFieldValue(fieldName: String)

Get field value by fieldName.

getFieldInstance(fieldName: String)

Get field react public instance by fieldName.

setFieldsValue(obj: Object)

Set fields value by kv object.

setFieldsInitialValue(obj: Object)

Set fields initialValue by kv object. use for reset and initial display/value.

setFields(obj: Object)

Set fields by kv object. each field can contain errors and value member.

validateFields([fieldNames: String[]], [options: Object], callback: (errors, values) => void)

Validate and get fields value by fieldNames.

options is the same as validate method of async-validator. And add force.

options.force: Boolean

Defaults to false. Whether to validate fields which have been validated(caused by validateTrigger).

getFieldsError(names): Object{ [name]: String[] }

Get inputs' validate errors.

getFieldError(name): String[]

Get input's validate errors.

isFieldValidating(name: String): Bool

Whether this input is validating.

isFieldsValidating(names: String[]): Bool

Whether one of the inputs is validating.

isFieldTouched(name: String): Bool

Whether this input's value had been changed by user.

isFieldsTouched(names: String[]): Bool

Whether one of the inputs' values had been changed by user.

resetFields([names: String[]])

Reset specified inputs. Defaults to all.

isSubmitting(): Bool (Deprecated)

Whether the form is submitting.

submit(callback: Function) (Deprecated)

Cause isSubmitting to return true, after callback called, isSubmitting return false.

rc-form/lib/createDOMForm(option): Function

createDOMForm enhancement, support props.form.validateFieldsAndScroll

validateFieldsAndScroll([fieldNames: String[]], [options: Object], callback: (errors, values) => void)

props.form.validateFields enhancement, support scroll to the first invalid form field, scroll is the same as dom-scroll-into-view's function parameter config.

options.container: HTMLElement

Defaults to first scrollable container of form field(until document).

Notes

  • Do not use stateless function component inside Form component: facebook/react#6534

  • you can not set same prop name as the value of validateTrigger/trigger for getFieldProps

<input {...getFieldProps('change',{
  onChange: this.iWantToKnow // you must set onChange here or use getFieldDecorator to write inside <input>
})}>
  • you can not use ref prop for getFieldProps
<input {...getFieldProps('ref')} />

this.props.form.getFieldInstance('ref') // use this to get ref

or

<input {...getFieldProps('ref',{
  ref: this.saveRef // use function here or use getFieldDecorator to write inside <input> (only allow function)
})} />

Test Case

npm test
npm run chrome-test

Coverage

npm run coverage

open coverage/ dir

License

rc-form is released under the MIT license.

More Repositories

1

slider

React Slider
JavaScript
2,962
star
2

calendar

React Calendar
JavaScript
1,681
star
3

table

React Table
TypeScript
1,183
star
4

tree

React Tree
TypeScript
1,113
star
5

field-form

⚑️ React Performance First Form Component
TypeScript
914
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