Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useForm equivalent in class component

I moved a functional component to class component recently and don't find the equivalent of useForm when using a class. Here is the code I used before:

var commentField = form.getState()["active"].replace(new RegExp("parameter_info$"), "comment");
form.change(commentField, result.comment);

With this, I was able to link two dynamicaly generated inputs.
How can I do it using a class?

like image 842
Borhink Avatar asked Dec 07 '25 08:12

Borhink


1 Answers

FinalForm docs says useForm() is used internally inside useField(), <Field/>, and <FormSpy/>., so it's possible to write equivalent code using FormSpy:

  class Updater extends React.Component {
    componentWillReceiveProps(nextProps) {
      var commentField = this.props.form.getState()["active"].replace(new RegExp("parameter_info$"), "comment");
      this.props.form.change(commentField, result.comment);
    }
  
    render() {
      return null;
    }
  }

You need to render <FormSpy subscription={{ values: true }} component={Updater} /> somewhere in your form to make it work.

Note that you can use final-form-calculate package to implement calculations between fields.

like image 81
Evgeny Timoshenko Avatar answered Dec 10 '25 01:12

Evgeny Timoshenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!