React - binding `this` to an imported function

Viewed 6281

In my React app, I have a handful of functions that I'd like to be able to access across a few similar components... however, I want to bind this to the shared functions so that they can do things like update the component state, etc... however, it seems that importing the functions and then trying to bind this in the 'typical' React manner does not work.

Here's an illustration of what I'd like to accomplish - in this case, clicking the rendered button would call the function from the imported shared function file and update the component state:

//shared_functions.js
const sharedFunctions = {
    testFunction = () => {
        this.setState({functionWasRun: true})
    }
}


//MyComponent.jsx
import React, { Component } from 'react';
import sharedFunctions from '../static/scripts/shared_functions.js';
let { testFunction } = sharedFunctions;

class MyComponent extends Component {
    constructor(props){
        super(props);
        this.testFunction = this.testFunction.bind(this)
        this.state = {
            functionWasRun: false
        }
    }

    render(){
        return(
            <div>
                <button onClick={this.testFunction}>Click</button>
            </div>
        )
    }
}

Trying to run this code as is will return an error like:

Uncaught (in promise) TypeError: Cannot read property 'bind' of undefined

and I get what that's all about... but what I'd like to know is: is it possible to bind this to an imported function?

I'm starting to get a lot of similar-looking functions popping up throughout my app and I'd love to simplify things by abstracting them into a shared script, but I'm not sure how to achieve the typical this binding that's needed to achieve state-setting.

3 Answers

I used it in the following way:

In constructor:

this.handleChange = handleChange.bind(this);

In the imported file (be careful, no arrow):

export const handleChange = function handleChange(event) 
{
  const { name, value } = event.target;
  this.setState({
    [name]: object
  });
};
Related