Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
redux-form
Advanced tools
redux-form is a library that allows you to manage form state in Redux. It provides a way to keep form state in a Redux store, making it easier to manage complex forms and their validation, submission, and other behaviors.
Form Creation
This code demonstrates how to create a simple form using redux-form. The `Field` component is used to define form fields, and the `reduxForm` higher-order component is used to connect the form to Redux.
import React from 'react';
import { Field, reduxForm } from 'redux-form';
let SimpleForm = props => {
const { handleSubmit } = props;
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="firstName">First Name</label>
<Field name="firstName" component="input" type="text" />
</div>
<button type="submit">Submit</button>
</form>
);
};
SimpleForm = reduxForm({
form: 'simple'
})(SimpleForm);
export default SimpleForm;
Form Validation
This code demonstrates how to add validation to a form using redux-form. The `validate` function checks for errors and returns an object with error messages, which are then used by redux-form to display validation errors.
import React from 'react';
import { Field, reduxForm } from 'redux-form';
const validate = values => {
const errors = {};
if (!values.firstName) {
errors.firstName = 'Required';
}
return errors;
};
let ValidatedForm = props => {
const { handleSubmit } = props;
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="firstName">First Name</label>
<Field name="firstName" component="input" type="text" />
</div>
<button type="submit">Submit</button>
</form>
);
};
ValidatedForm = reduxForm({
form: 'validated',
validate
})(ValidatedForm);
export default ValidatedForm;
Form Submission
This code demonstrates how to handle form submission using redux-form. The `handleSubmit` function is passed a `submit` function that processes the form data.
import React from 'react';
import { Field, reduxForm } from 'redux-form';
const submit = values => {
console.log('Form data:', values);
};
let SubmitForm = props => {
const { handleSubmit } = props;
return (
<form onSubmit={handleSubmit(submit)}>
<div>
<label htmlFor="firstName">First Name</label>
<Field name="firstName" component="input" type="text" />
</div>
<button type="submit">Submit</button>
</form>
);
};
SubmitForm = reduxForm({
form: 'submit'
})(SubmitForm);
export default SubmitForm;
Formik is a popular form library for React that provides a simpler API compared to redux-form. It focuses on reducing boilerplate and improving performance by not relying on Redux for form state management. Formik is often preferred for its ease of use and flexibility.
React Hook Form is a library that uses React hooks to manage form state and validation. It is known for its minimal re-renders and high performance. Unlike redux-form, it does not require Redux and is often chosen for its simplicity and performance benefits.
Final Form is a framework-agnostic form state management library that can be used with React through the react-final-form package. It offers similar functionality to redux-form but is designed to be more lightweight and flexible, without the need for Redux.
#redux-form
@reduxForm
is an ES7 decorator to for enabling a form in React to use Redux to store all of
its state.
npm install --save redux-form
Why would anyone want to do this, you ask? React a perfectly good way of keeping state in each component! The reasons are twofold.
When used in conjunction with React Hot Loader, you can modify your components, rebuild your app and immediately see your changes without losing your form data. This may seem trivial, but the minutes of refilling out forms in a develomnet environment really add up.
By removing the state from your form components, you inherently make them easier to understand, test, and debug. The React philosophy is to always try to use props
instead of state
when possible.
When you are adding your reducers to your redux store, add a new one with createFormReducer(])
.
import { createStore, combineReducers } from 'redux';
import { createFormReducer } from 'redux-form';
const reducers = {
// ... your other reducers here ...
createFormReducer('contacts', ['name', 'address', 'phone'], contactValidation)
}
const reducer = combineReducers(reducers);
const store = createStore(reducer);
Then, on your form component, add the @reduxForm('contacts')
decorator.
import React, {Component, PropTypes} from 'react';
import reduxForm from 'redux-form';
@reduxForm('contacts')
export default class ContactForm extends Component {
static propTypes = {
data: PropTypes.object.isRequired,
errors: PropTypes.object.isRequired,
handleChange: PropTypes.func.isRequired,
validate: PropTypes.func.isRequired,
reset: PropTypes.func.isRequired
}
render() {
const {
data: {name, address, phone},
errors: {name: nameError, address: addressError, phone: phoneError}
} = this.props;
return (
<form>
<label>Name</label>
<input type="text" value={name} onChange={handleChange('name')}/>
{nameError ? <div>{nameError}</div>}
<label>Address</label>
<input type="text" value={address} onChange={handleChange('address')}/>
{addressError ? <div>{addressError}</div>}
<label>Phone</label>
<input type="text" value={phone} onChange={handleChange('phone')}/>
{phoneError ? <div>{phoneError}</div>}
</form>
);
}
}
Notice that we're just using vanilla <input>
elements there is no state in the ContactForm
component. I have left handling onSubmit
as an excercise for the reader. Hint: your data is in this.props.data
.
You will need to supply your own validation function, which is in the form ({}) => {}
and takes in all your data and spits out error messages. For example:
function contactValidation(data) {
const errors = {};
if(!data.name) {
errors.name = 'Required';
}
if(data.address && data.address.length > 50) {
errors.address = 'Must be fewer than 50 characters';
}
if(!data.phone) {
errors.phone = 'Required';
} else if(!/\d{3}-\d{3}-\d{4}/.test(data.phone)) {
errors.phone = 'Phone must match the form "999-999-9999"'
}
return errors;
}
You get the idea.
Each form has a sliceName
. That's the key in the Redux store tree where the data will be mounted.
sliceName
: stringthe name of your form and the key to where your form's state will be mounted in the Redux store
a list of all your fields in your form.
your validation function
sliceName
: stringthe name of your form and the key to where your form's state will be mounted in the Redux store
Check out the react-redux-universal-hot-example project to see redux-form
in action.
This is an extremely young library, so the API may change. Comments and feedback welcome.
FAQs
A higher order component decorator for forms using Redux and React
The npm package redux-form receives a total of 220,976 weekly downloads. As such, redux-form popularity was classified as popular.
We found that redux-form demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 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.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.