dt1000 dt1000 - 1 year ago 136
React JSX Question

React - Redux, submit a form with data from child components

I have a component which is a form, with a number of child components. What is the best way to consolidate the data from all of the child components, when submitting the form? Below is one idea, is this the correct method? I pass a reference to a function that will update a property of a form upon change in a component. What is best practice? Thanks.

import React from 'react';
import { Component , PropTypes} from 'react';
import { connect } from 'react-redux';
import { saveData } from '../actions/index'
import {bindActionCreators} from 'redux';

export default class MyClass extends Component {
constructor(props) {
super (props);
this.formData = {};
this.setFormData = this.setFormData.bind(this);
this.onSubmitHandler = this.onSubmitHandler.bind(this);

setFormData(key, value){
this.formData[key] = value;


render (){
return (
<form onSubmit = {this.onSubmitHandler} >
<div >
<NameComponent setFormData = {this.setFormData}/>
<AddressComponent setFormData = {this.setFormData}/>
//...lots more components

export default connect( mapStateToProps, {saveData)(MyClass)

leo leo
Answer Source

Yes, this approach is correct, because children are generally expected to delegate to parent that is responsible for them. In fact, that's how Redux Form works. <Field /> input components delegate their state to a Higher Order <Form /> wrapper.

The problem with your approach is that you have to do a lot of repetitive stuff on your own (such as calling onChange, delegating the value etc).

We use Redux Form for one of our projects and it's great as it integrates forms, react and redux. I find myself writing much less code and there is build in validation for both remote, local submission, submission from child components and other neat stuff.

My suggestion is to go with Redux Form instead of reinventing the wheel.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download