How to get floatValue automatically from react-number-format inside a antd Form.Item?

407 Views Asked by At

I'm looking for a way to antd Form get automatically a floatValue from react-number-format.

      `<Form.Item
        label="My label"
        name="fator"
      >
        <NumericFormat
          thousandSeparator="."
          decimalSeparator=","
          decimalScale={2}
          prefix="R$"
          fixedDecimalScale={true}
          onValueChange={(values, sourceInfo) => {
            setState({
              ...state,
              fator: values.floatValue!,
            });
          }}
        />
      </Form.Item>`

Some people used onValueChange to get floatValue, but I do not know if it is the only way or the best way to get that value. On that way, we have to check each field to assign the correct value. In my opinion, it is not the best way. It is so manually work.

const submit = async (values: stateModel) => { values.fator = state.fator; ... ... await doRegister(values); .. }

How the best way to solve the problem?

I tried using some replacement on values returned from form submit, but it is not the best way to solve the problem.

1

There are 1 best solutions below

0
Muhammad Nouman Rafique On

You can solve this issue by creating a custom Number Field, which takes value and onChange as props.

const CustomNumberField = ({ value, onChange }) => {
  return (
    <NumericFormat
      value={value}
      thousandSeparator='.'
      decimalSeparator=','
      decimalScale={2}
      prefix='R$'
      fixedDecimalScale={true}
      onValueChange={(values, sourceInfo) => {
        onChange(values.floatValue);
      }}
    />
  );
};

Now the main Form will look like this:

const App = () => {
  return (
    <Form
      onFinish={(values) => {
        console.log(values); // { factor: 12 }
      }}
    >
      <Form.Item label='My label' name='fator'>
        <CustomNumberField />
      </Form.Item>
      {/* OR */}
      {/* <Form.Item name='field'>
        {(control, meta, form) => {
          return <CustomNumberField {...control} />;
        }}
      </Form.Item> */}
      <Button htmlType='submit'>Submit</Button>
    </Form>
  );
};

Q: Where that value & onChange prop come from?

When you pass name prop to Form.Item, the field inside the Form.Item is now controlled by Form. You can either pass a ReactElement or a function. For ReactElement, it pass two props value & onChange. For callback function, it looks like this:

children?: React.ReactElement | ((control: ChildProps, meta: Meta, form: FormInstance<Values>) => React.ReactNode);

interface ChildProps {
    [name: string]: any;
}

interface Meta {
    touched: boolean;
    validating: boolean;
    errors: string[];
    warnings: string[];
    name: InternalNamePath;
}

type InternalNamePath = (string | number)[];