Mukund Kumar
Mukund Kumar

Reputation: 23231

How to make controlled input using redux-form?

I have one form component, in which we have one input field.once user enter a digit to input field and press submit, it should become two time of that input value.

import {Field} 'redux-form'; 
class Multiply extends React.Component {

  onInputChange = (stateKey) => (e) => {
    this.setState({ [stateKey]: e.currentTarget.value.trim() });
  };

  onSubmit = () => {
    this.setState({ volume: this.state.volume *2  });
  };

  render(): JSX.Element {
    return (
      <div>
        <div>
          <form onSubmit={this.props.handleSubmit(this.onSubmit)}>
            <Field
              name="volume"
              placeholder="Volume"
              component={renderInput}
              type="number"
              value={this.state.volume}
              onChange={this.onInputChange('volume')}
              validate={required}
            />

            <div>
              <button type="submit">
                Multiply by 2
              </button>
            </div>
          </form>
        </div>
      </div>
    );
  }
}

once i click on button, value doesn't get change. but instead of <field> if i use <input> then it works fine. why ?

Upvotes: 2

Views: 2150

Answers (1)

gustavohenke
gustavohenke

Reputation: 41440

Redux Form inputs are dictated by their Redux state. This means you have to use its API to deal with them, as Field is giving your renderInput function an input value that equals whatever is in the Redux store for that field name.

What you'll need to do is

  1. Inject the field value. A good way of doing so is by using formValues()
  2. Inject a function that dispatches a change action for that form and for that field
  3. Call such function in your button.

This is the gist of it:

const MyForm = ({ double }) => {
    /* Your form implementation, then */
    <button type="submit" onClick={double}>Double and submit</button>
};

const mapDispatchToProps = (dispatch, props) => ({
    double: () => dispatch(change("foo", "number", props.number * 2))
});

const WithDoublingFunction = formValues("number")(connect(null, mapDispatchToProps)(MyForm));

export default reduxForm({
    form: "foo",
    // the rest of your config
})(WithDoublingFunction);

Here's a working sandbox of such functionality

Upvotes: 2

Related Questions