Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
The rc-form package is a form management library for React. It provides a set of utilities to manage form state, validation, and submission, making it easier to handle complex forms in React applications.
Form Creation
This feature allows you to create forms with validation rules. The `createForm` function is used to wrap the form component, and `getFieldDecorator` is used to register form fields with validation rules.
```jsx
import React from 'react';
import { createForm } from 'rc-form';
class MyForm extends React.Component {
handleSubmit = () => {
this.props.form.validateFields((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
};
render() {
const { getFieldDecorator } = this.props.form;
return (
<form onSubmit={this.handleSubmit}>
<div>
{getFieldDecorator('username', {
rules: [{ required: true, message: 'Please input your username!' }],
})(<input type="text" placeholder="Username" />)}
</div>
<button type="submit">Submit</button>
</form>
);
}
}
export default createForm()(MyForm);
```
Field Validation
This feature allows you to add validation rules to form fields. In this example, the email field is validated to ensure it is a valid email address and is required.
```jsx
import React from 'react';
import { createForm } from 'rc-form';
class MyForm extends React.Component {
handleSubmit = () => {
this.props.form.validateFields((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
};
render() {
const { getFieldDecorator } = this.props.form;
return (
<form onSubmit={this.handleSubmit}>
<div>
{getFieldDecorator('email', {
rules: [
{ type: 'email', message: 'The input is not valid E-mail!' },
{ required: true, message: 'Please input your E-mail!' }
],
})(<input type="email" placeholder="Email" />)}
</div>
<button type="submit">Submit</button>
</form>
);
}
}
export default createForm()(MyForm);
```
Dynamic Form Fields
This feature allows you to dynamically add form fields. The `addField` method updates the state to add new fields, and `getFieldDecorator` is used to register these fields with validation rules.
```jsx
import React from 'react';
import { createForm } from 'rc-form';
class DynamicForm extends React.Component {
state = { keys: [] };
addField = () => {
const { keys } = this.state;
this.setState({ keys: keys.concat(keys.length) });
};
handleSubmit = () => {
this.props.form.validateFields((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
};
render() {
const { getFieldDecorator } = this.props.form;
const { keys } = this.state;
return (
<form onSubmit={this.handleSubmit}>
{keys.map(k => (
<div key={k}>
{getFieldDecorator(`field-${k}`, {
rules: [{ required: true, message: 'Please input a value!' }],
})(<input type="text" placeholder="Dynamic Field" />)}
</div>
))}
<button type="button" onClick={this.addField}>Add Field</button>
<button type="submit">Submit</button>
</form>
);
}
}
export default createForm()(DynamicForm);
```
Formik is a popular form management library for React. It provides a set of tools to handle form state, validation, and submission. Compared to rc-form, Formik offers a more modern API and better integration with React hooks.
React Hook Form is a performant, flexible, and extensible form library for React. It leverages React hooks to manage form state and validation. It is known for its minimal re-renders and easy integration with existing components, making it a strong alternative to rc-form.
Redux Form is a library that integrates form state management with Redux. It allows you to manage form state in a centralized Redux store. While it offers powerful features, it can be more complex to set up compared to rc-form.
React High Order Form Component.
npm install
npm start
open http://localhost:8000/examples/
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);
Expo preview
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);
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 |
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
The returned function of createForm(). It will pass an object as prop form
with the following members to WrappedComponent:
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>
This input's unique name.
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 |
getValueFromEvent
function defaultGetValueFromEvent(e) {
if (!e || !e.target) {
return e;
}
const { target } = e;
return target.type === 'checkbox' ? target.checked : target.value;
}
{
validateTrigger: 'onBlur',
rules: [{required: true}],
}
// is the shorthand of
{
validate: [{
trigger: 'onBlur',
rules: [{required: true}],
}],
}
Similar to getFieldProps
, but add some helper warnings and you can write onXX directly inside React.Node props:
<form>
{getFieldDecorator('name', otherOptions)(<input />)}
</form>
Get fields value by fieldNames.
Get field value by fieldName.
Get field react public instance by fieldName.
Set fields value by kv object.
Set fields initialValue by kv object. use for reset and initial display/value.
Set fields by kv object. each field can contain errors and value member.
Validate and get fields value by fieldNames.
options is the same as validate method of async-validator.
And add force
and scroll
. scroll
is the same as dom-scroll-into-view's function parameter config
.
Defaults to false. Whether to validate fields which have been validated(caused by validateTrigger).
Get inputs' validate errors.
Get input's validate errors.
Whether this input is validating.
Whether one of the inputs is validating.
Whether this input's value had been changed by user.
Whether one of the inputs' values had been changed by user.
Reset specified inputs. Defaults to all.
Whether the form is submitting.
Cause isSubmitting to return true, after callback called, isSubmitting return false.
createDOMForm enhancement, support props.form.validateFieldsAndScroll
props.form.validateFields enhancement, support scroll to the first invalid form field
Defaults to first scrollable container of form field(until document).
Do not use stateless function component inside Form component: https://github.com/facebook/react/pull/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>
})}>
<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)
})} />
npm test
npm run chrome-test
npm run coverage
open coverage/ dir
rc-form is released under the MIT license.
FAQs
React High Order Form Component
The npm package rc-form receives a total of 62,136 weekly downloads. As such, rc-form popularity was classified as popular.
We found that rc-form demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 7 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.