Search code examples
javascriptreactjsecmascript-6arrow-functions

Changing class state from an imported function in ReactJS


I am trying to change the state of a class from an imported named component so I only need to write the code once. Is this even possible?

I have 3 files ( Login, ForgotPassword, Register ). On ALL of these files I am listening for an "onChange" event on the input fields that all do the same thing as show below:

onChange method:

onChange = (e) => {
    this.setState(() => ({ errors: {} }));

    let fields = this.state.fields;
    fields[e.target.name] = e.target.value;
    this.setState(() => {
        return {
            fields
        }
    });
};

I'd really like to import this as a named method along with some others that are working already:

import { onFocus, onBlur, onChange } from './Utils/Input';

The issue is (as seen above in the onChange code), that I need to update the class state from this method.

Is this at all possible? I am very new to React, so I might be going about this in the completely wrong way.

Thank you in advance!


Solution

  • When trying to update the state of a component you are always updating the state regarding to a particular this.

    You are trying to write on* functions which are independent of the instances you are working with. So it makes no sense to use "this" inside those.

    You could pass the instance of the Class to the on-function like this:

    https://codesandbox.io/s/focused-cache-zzfvp