Search code examples
javascriptreactjsredux-form

Update one Field based on another


As a part of my form I have a field for selecting items and a button which the client clicks in order to add the items to their list of units. I wish to show the list of units selected by the user in the units text field. How do I implement the onclick function for the button so that it takes the currently selected value for the select component before appending it to the list as presented by the textbox? I have a separate save button which will take the form data and send it to the backend when clicked.

let EditUserForm = (props) => {
    const { handleSubmit, units } = props;
    return (
        <form onSubmit={handleSubmit}>

            <Field name="units" component="input" type="text" readOnly/> 

            <Field name="unit" component="select" >
            {
                units.map(u => <option value={u} key={u}>{u}</option>)
            }
            </Field>

            <button type="button" onClick={props.updateUserUnits}>Add unit</button>

        </form>
    );
};

Solution

  • You could do something like in the code below. This combines several redux-form concepts.

    Basically you want to intercept the onChange event from the select component, so you can attach some logic to it.

    In this case we'll use the change prop that is passed down by redux-form. This will allow you to change the value of another field in the form.

    Combine this with the formValueSelector which allows you to get a value from a specific form field.

    import React from 'react'
    import { connect } from 'react-redux';
    import { Field, FieldArray, formValueSelector, reduxForm } from 'redux-form'
    
    const EditUser = (props) => {
        const { change, handleSubmit, selectedUnits = [], units } = props;
    
        const handleUnitChange = (event, value) => {
          const newUnits = [ ...selectedUnits, value ];
    
          change('units', newUnits);
        }
    
        return (
            <form onSubmit={handleSubmit}>
                <Field name="units" component="input" type="text" readOnly/> 
    
                <Field name="unit" component="select" onChange={handleUnitChange}>
                  {units.map(u => <option value={u} key={u}>{u}</option>)}
                </Field>
    
                <button type="button" onClick={props.sendData}>Add unit</button>
            </form>
        );
    };
    
    const form = 'editUserForm';
    
    const EditUserForm = reduxForm({
      form
    })(EditUser);
    
    const selector = formValueSelector(form);
    
    export default connect(state => ({
      selectedUnits: selector(state, 'units')
    }))(EditUserForm);