Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen to onChange of the Field component in React-Final-Form?

Redux-form "Field" component provides onChange property. A callback that will be called whenever an onChange event is fired from the underlying input. This callback allows to get "newValue" and "previousValue" for the Field.

React-final-form "Field" component doesn't have this property.

So, how I can get the same functionality?

like image 619
Maksim Boltik Avatar asked May 20 '18 15:05

Maksim Boltik


2 Answers

I haven't used redux-form, but I added a super simple wrapper around the Field component to listen to onChange like this:

const Input = props => {

    const {
        name, 
        validate, 
        onChange,
        ...rest
    } = props;

    return (
        <Field name={name} validate={validate}>
            {({input, meta}) => {
                return (
                    <input 
                        {...input}
                        {...rest}
                        onChange={(e) => {
                            input.onChange(e); //final-form's onChange
                            if (onChange) { //props.onChange
                                onChange(e);
                            }
                        }}
                    />
            )}}
        </Field>
    );
};
like image 173
orszaczky Avatar answered Oct 22 '22 04:10

orszaczky


One could use the Field's parse attribute and provide a function that does what you need with the value:

<Field
  parse={value => {
    // Do what you want with `value`
    return value;
  }}
  // ...
/>
like image 36
robsco Avatar answered Oct 22 '22 04:10

robsco