Using a Custom onChange Event on a Mantine-Form Input

I'd like to do some responsive logic, where when a value changes it triggers other values to change in a form.

I'm using mantine forms, and so far the best approach I've been able to come upon is something like the following:

const onUserChange = (e) => {
   // form.values.acounts.user contains the previous user value
   // e contains the incoming update to it
   form.setFieldValue('other.property.associated.with.user', e);
 }

 <Select label="User"
              data={users}
              {...form.getInputProps(`accounts.user`)}
              onChange={(e) => {
                onUserChange(e);
                form.getInputProps(`accounts.user`).onChange(e)
              }}
      ></Select>

This approach 'seems' to be decent, but I'm not sure if there's a better way. Anyone come across this before? Maybe some neat callback syntax or something?

3 Answers

Seems like a legitimate way to override the libraries onChange handler. However, I would use onChangeUser to also set the user's value:

const onUserChange = ({ target }) => {
  const { value } = target;
  form.setFieldValue('other.property.associated.with.user', fn(value)); // fn transforms the value for the associated property
  form.setFieldValue('accounts.user', value);
};

<Select label="User"
  data={users}
  {...form.getInputProps('accounts.user')}
  onChange={onUserChange}
></Select>
1

I encountered similar situation. In my case I have to provide search-suggestions using. For that I have to set debouncedState on every change.

In your case I suggest add an extra if statement before calling onChange(e)

<Select label="User"
          data={users}
          {...form.getInputProps(`accounts.user`)}
          onChange={(e) => {
            onUserChange(e);
            if(form.getInputProps(`accounts.user`).onChange)
              form.getInputProps(`accounts.user`).onChange(e)
          }}
  ></Select>

It turns out the library doesn't do much magic in regards to the onchange, and effectively just sets the form value via form.setFieldValue. As long as the onchange provided sets the value you don't need to re-reference the onchange gotten from 'getInputProps'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest