Skip to content Skip to sidebar Skip to footer

How To Properly Import Function In A Reactjs File

I'm having trouble importing a function in react. I used export default to export the function. However after importing it I tried to bind it in the render function but I got an er

Solution 1:

It looks like you have an extra bracket in there, also, the imported function will just be onSignUp not this.onSignUp.

import  onSignUp  from'../../functions/onsignup'classModalExampleextendsReact.Component {

  constructor(props) {
    super(props);
    this.onSignUp = onSignUp.bind(this);
  }

  render(){
    return(...)
  }
}

You should bind the function in the ctor or alternatively assign it in the class to onSignup like this:

import  onSignUp  from'../../functions/onsignup'classModalExampleextendsReact.Component {

  constructor(props) {
    super(props);
  }

  onSignUp = onSignUp.bind(this);

  render(){
    return(...)
  }
}

(I think)

Solution 2:

Does this mean the function did not correctly import?

Possibly yes.

How do I correctly import it in React?

import exportedFunction from './directorypath';// if exported using default

import { exportedFunction } from './directorypath'; // if default not used while exporting.

A code snippet of the component would give a better picture of the problem.

Solution 3:

Maybe you can put you declaration in the constructor like this referring to the onSignUp you imported instead of this.onSignUp that doesn't exists :

constructor(props) {
    super(props);
    this.onSignUp = onSignUp.bind(this);
}

Solution 4:

Can you show us the function in the onSignUp file? you might not need to bind it depending on what function it is, however...

this.onSignp = this.onSignUp.bind(this);

Doing this in the constructor will assume you are initializing a new function not the one you are importing, use this instead.

this.onSignp = onSignUp.bind(this);

And make sure you are properly defining it from where you are declaring

Solution 5:

If you are importing a function from out side of React class, then no need to bind it inside React class. You just import and use it. see the below..

functions/onsignup.js

function defined and export here.

constonSignUp = () =>{
// function code here
}

exportdefault signup;

ModalExample.js

import the function here and use.

importReact, {Componenet} from'react';
import  onSignUp  from'../../functions/onsignup'classModalExampleextendsReact.Component {
    constructor(props) {
        super(props);
    }


    render(){
      return(
         <buttononClick={()=>onSignUp()} />
      )
    }
}

Post a Comment for "How To Properly Import Function In A Reactjs File"