Today I Learned

This project exists to catalogue the sharing & accumulation of knowledge as it happens day-to-day. Posts have a 200-word limit, and posting is open to any Rocketeer as well as selected friends of JetRockets. We hope you enjoy learning along with us.

Custom onChange in React Final Form

Let’s take a case when we need to call our own function to change a state of a specific field in a form (our react final form).

Here is a way to do the exact that: You should pass your function as a parameter and after that just call it inside of the onChange method

Example:

const FormGroupAdapter = ({ input, inputOnChange }) => {
    const inputProps = {
        ...input,
        onChange: e => {
            input.onChange(e);
            inputOnChange && inputOnChange(e);
        }
    };

    return <input {...inputProps} />;
};

const handleChange = event => {
    console.log("!!!", event.target.value);
};

const App = () => (
    <Form
        ...
        render={({ handleSubmit, reset, submitting, pristine, values }) => (
            <form onSubmit={handleSubmit}>
                <div>
                    <label>some label</label>
                    <Field
                        name="someField"
                        component={FormGroupAdapter}
                        inputOnChange={handleChange}
                    />
                </div>
                ...
            </form>
        )}
    />
);

Live example

Looking for help? At JetRockets, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.