Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  143] [ 1]  / answers: 1 / hits: 18425  / 8 Years ago, fri, december 23, 2016, 12:00:00

I have two functions that look like this:



  primaryImageLoaded () {
this.setState({primaryImageLoaded: true})
}

secondaryImageLoaded () {
this.setState({ secondaryImageLoaded: true })
}


They are called like this(using react):



onLoad={this.secondaryImageLoaded.bind(this)


This feels excessive and I would like to have just one function and pass the state-variable as a parameter, but how can I pass an additional argument to .bind? and is it possible to use a variable as key in the object i'm passing to setState?


More From » reactjs

 Answers
72

You can pass additional arguments to bind that will be passed when your function is invoked:



this.secondaryImageLoaded.bind(this, arg1, arg2)



If you are using ECMAScript 2015 and onwards, you can use a variable as a key by wrapping it in square brackets:



this.setState({
[myVar]: value
});


So you could rewrite it to be more like:



function imageLoaded(which) {
this.setState({
[which]: true
});
}

onLoad={this.imageLoaded.bind(this, 'secondary')}

[#59583] Thursday, December 22, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bethv

Total Points: 215
Total Questions: 101
Total Answers: 89

Location: Angola
Member since Wed, Jun 2, 2021
3 Years ago
;