Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - binding `this` to an imported function

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.

like image 460
skwidbreth Avatar asked Aug 05 '17 01:08

skwidbreth


People also ask

How do you use imported functions in React?

To import a function from another file in React:Export the function from file A , e.g. export function sum() {} . Import the function in file B as import {sum} from './another-file' . Use the imported function in file B .

How do you bind a function in React JS?

function. bind(this,[arg1...]); Parameter: It accepts two parameters, the first parameter is the this keyword used for binding and the second parameter is the sequence of arguments that are passed as a parameter and are optional.

Why do we need to bind this in React?

Binding methods helps ensure that the second snippet works the same way as the first one. With React, typically you only need to bind the methods you pass to other components. For example, <button onClick={this.handleClick}> passes this.handleClick so you want to bind it.

How do you call a function from another file in React JS?

To call JavaScript function from another file in React, we export the function we want to call and then import it. export const plusSlides = (n) => { showSlides((slideIndex += n)); }; in slideShow.


1 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
  });
};
like image 64
Karens Avatar answered Oct 22 '22 14:10

Karens