How to prevent react-final-form from rendering an specific input

578 Views Asked by At

I have a react-final-form form, which has 2 inputs. Let's call them from and to.

What I want to do is that whenever input from changes, I set a value for input to based on input from's value.

I do that in validate function because i don't know where else i can do that. And it causes re-rendering the component in a loop.

Since I change the value of to in validate, it causes validate function to run again and again and again. How can I avoid that?

The actual code is much more complex than this but this is where i run into problems.

Thanks

const validate = (v) => {
  const calculateFrom = calculate(v.from);

  window.setTo(calculateFrom);
};
<Form
  onSubmit={onSubmit}
  validate={validate}
  mutators={{
    setTo: (a, s, u) => {
      u.changeValue(s, 'to', () => a[0]);
    },
    setMax: (a, s, u) => {
      u.changeValue(s, 'from', () => getMaxBalance(selectedAsset1));
    },
  }}
  subscription={{ submitting: true, pristine: true }}
  render={({
    form,
    pristine,
    invalid,
    handleSubmit,
  }) => {
    if (!window.setTo) {
      window.setTo = form.mutators.setTo;
    }

    return (
      <form onSubmit={handleSubmit}>
<Field name="from">
  {({ input, meta }) => (
    <Input
      type="number"
      placeholder="123"
      size="input-medium"
      input={input}
      meta={meta}
    />
  )}
</Field>

<Field name="to">
  {({ input, meta }) => (
    <Input
      type="number"
      placeholder="123"
      size="input-medium"
      input={input}
      meta={meta}
    />
  )}
</Field>
/>
1

There are 1 best solutions below

0
Petru-Cristian Boza On

First of all you could use an existing decorator https://codesandbox.io/s/oq52p6v96y

I'm not really sure why it is re-rendering infinitely. Might have something to do with reusing the function setTo that you put on the window.

If you don't want to add that mutator library I'd try the following solutions. use parse prop on the the Field where you can get the value and compare it with the other value that you need and return exactly what is should be check attached example parse prop

Final form allows to nest Fields inside custom components so you could just handle everything there by using useForm hook