purezen purezen - 5 months ago 26x
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.


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

onChangeBackgroundColor(backgroundColor) {
backgroundColor: backgroundColor

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

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

I am able to call a function fine without arguments like

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/

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.