purezen purezen - 6 months ago 30
Javascript Question

How to call a function with arguments in an ES6 class?

I am making an app in Reactjs using an ES6 class for a component.
The code works as intended until I want to call a function inside the class with arguments.

SampleClass.js

class SampleClass extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
backgroundColor: 'yellow'
}
}

onChangeBackgroundColor(backgroundColor) {
this.setState({
backgroundColor: backgroundColor
})
}

render() {
return <div style={{backgroundColor: this.state.backgroundColor, padding: 10}}>
<span onClick={this.onChangeBackgroundColor.bind(this)} style={{background: 'white'}}>
Change element style
</span>
</div>
}
}

React.render(<SampleClass />, document.getElementById('container'));


I am able to call a function fine without arguments like
this.onChangeBackgroundColor.bind(this)
.

However, when I try passing an argument to the function, I get an error in the console
Uncaught TypeError: Cannot read property 'bind' of undefined
.

Ref fiddle: https://jsfiddle.net/purezen/s6ap3m8s/3/

Answer
this.onChangeBackgroundColor.bind(this, arg1, arg2)

Your arguments should go in the bind call, after this, if you want them to be bound to the function.

Comments