What is Redux Form?
Redux was mainly developed to address the challenges of managing the state in large and complex JavaScript applications, particularly those built with the React library. It provides a centralized state store, promotes predictable data flow, and facilitates consistent development patterns.
- Redux is a state management library mostly used with React applications.
- Redux provides a predictable state container, making it easier to manage and manipulate the state of an application.
Redux Form
Redux Form is a library that integrates with Redux to manage the state of forms within a React application. It leverages the principles of Redux to handle the complex state management associated with forms.
Key features
Form state in the Redux store: The form state, including input values, errors, and other metadata, is stored in the Redux store.
Actions and reducers: Redux Form provides actions and reducers that handle form-related actions, such as input changes and form submissions.
Validation: It supports form validation, allowing developers to define validation rules for form fields.
Asynchronous operations: It handles asynchronous operations, such as submitting a form and managing the state during submission.
Setting up a React app with Redux Form
Follow the steps below to set up the React application with redux-form:
The following command will create the template React application project:
npx create-react-app redux-form-example
After creating a project, go to the newly created project folder using the command as follows:
cd redux-form-example
Now install the required packages using
npm:
npm install redux react-redux redux-form
Now replace the content of
src/App.jswith the following code:
// src/App.jsimport React from 'react';import { Provider } from 'react-redux';import { createStore, combineReducers } from 'redux';import { reducer as formReducer, reduxForm, Field } from 'redux-form';// Reducer for the form stateconst rootReducer = combineReducers({form: formReducer,});// Redux storeconst store = createStore(rootReducer);// Form componentconst RegistrationForm = props => {const { handleSubmit } = props;const submitForm = values => {// Handle form submission logic hereconsole.log(values);};return (<form onSubmit={handleSubmit(submitForm)}><div><label htmlFor="username">Username:</label><Field name="username" component="input" type="text" /></div><div><label htmlFor="password">Password:</label><Field name="password" component="input" type="password" /></div><button type="submit">Submit</button></form>);};// Connect the form component to the Redux storeconst ConnectedRegistrationForm = reduxForm({form: 'registrationForm',})(RegistrationForm);// App componentconst App = () => {return (<Provider store={store}><div className="App"><h1>Redux-Form Example</h1><ConnectedRegistrationForm /></div></Provider>);};export default App;
Now run the project using the command below:
npm start
Code example
All the steps mentioned above are followed, and the resultant project is as follows:
# Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in your browser. The page will reload when you make changes.\ You may also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can't go back!** If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) ### Analyzing the Bundle Size This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) ### Making a Progressive Web App This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) ### Advanced Configuration This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) ### Deployment This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) ### `npm run build` fails to minify This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
Code explanation
The explanation of the code is as follows:
Line 5: The
redux-formlibrary is imported, including thereducer(which manages form state) and the Redux store is created with a combined reducer that includes theformReducerfromredux-form.Lines 16–17: The
RegistrationFormcomponent is a simple form component that includes two input fields for ausernameandpassword, as well as a submit button. Theconst RegistrationForm = props => {...}function is component that receivespropsfromreduxForm(e.g.,handleSubmit).Line 33:
onSubmit={handleSubmit(submitForm)}in the<form>element indicates that when the form is submitted, thehandleSubmitfunction provided byreduxFormwill be called. This function is responsible for handling the submission of the form data.Lines 47–52:
<Provider store={store}>wraps the entire application with the ReduxProvidercomponent, providing the Redux store to all components in the app and theAppcomponent renders the<ConnectedRegistrationForm />component, which is now enhanced byredux-formand connected to the Redux store.Lines 60–65: The
reduxFormfunction is used as a higher-order component to wrapRegistrationForm. It gets a configuration object as an argument (in this case,{ form: 'registrationForm' }). This configuration object provides settings for the form, including a unique identifier ('registrationForm') for this form in the Redux store.
Conclusion
The use of redux-form facilitates the management of form state through Redux. The reduxForm higher-order component connects the form component to the Redux store, allowing for centralized state management, actions, and reducers to handle form-related interactions. This approach provides a clean and organized way to manage form state in larger React applications.
Free Resources