Reputation: 429
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 error saying TypeError: Cannot read property 'bind' of undefined
. Does this mean the function did not correctly import? How do I correctly import it in React?
import onSignUp from '../../functions/onsignup'
class ModalExample extends React.Component {
constructor(props) {
super(props);
}
this.onSignUp=this.onSignUp.bind(this);
}
render(){
return(...)
}
Upvotes: 0
Views: 234
Reputation: 156
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.
const onSignUp = () =>{
// function code here
}
export default signup;
ModalExample.js
import the function here and use.
import React, {Componenet} from 'react';
import onSignUp from '../../functions/onsignup'
class ModalExample extends React.Component {
constructor(props) {
super(props);
}
render(){
return(
<button onClick={()=>onSignUp()} />
)
}
}
Upvotes: 0
Reputation: 20047
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'
class ModalExample extends React.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'
class ModalExample extends React.Component {
constructor(props) {
super(props);
}
onSignUp = onSignUp.bind(this);
render(){
return(...)
}
}
(I think)
Upvotes: 1
Reputation: 165
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
Upvotes: 0
Reputation: 1279
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);
}
Upvotes: 0
Reputation: 1893
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.
Upvotes: 0