Reputation: 1196
for example I have this React component which simply does loading text. I have a problem with refactoring .bind(this) to es6 syntax.
var Loading = React.createClass({
getInitialState:() => {
this.originalText = 'Loading';
return {
text: 'Loading'
}
},
componentDidMount:function() {
let stopper = this.originalText + '...' ;
this.interval = setInterval(function(){
if(this.state.text === stopper) {
this.setState({
text:this.originalText
})
}else {
this.setState({
text: this.state.text + '.'
})
}
}.bind(this), 300)
},
render: function () {
return (
<div style={styles.container}>
<p style={styles.content}>{this.state.text}</p>
</div>
)
}
});
here I want to refactor
}.bind(this), 300)
to ES6 syntax. What would be solution.
Upvotes: 0
Views: 255
Reputation: 7258
You can replace:
this.interval = setInterval(function(){
/* ... */
}.bind(this), 300)
with:
this.interval = setInterval( () => {
/* ... */
}, 300)
That's because arrow functions automatically binds. BTW, I refactored all your component code to ES6:
class Loading extends React.Component {
constructor(props) {
super(props)
this.originalText = 'Loading'
this.state = {
text: 'Loading'
}
}
componentDidMount() {
let stopper = this.originalText + '...' ;
this.interval = setInterval( () => {
if(this.state.text === stopper) {
this.setState({
text:this.originalText
})
} else {
this.setState({
text: this.state.text + '.'
})
}
}, 300)
}
render() {
return (
<div style={styles.container}>
<p style={styles.content}>{this.state.text}</p>
</div>
)
}
}
Fiddle here: https://jsfiddle.net/mrlew/jgtyetwu/
Upvotes: 1
Reputation: 222369
function () { ... }.bind(this)
is what arrow function is supposed to do.
It is
this.interval = setInterval(() => { ... }, 300)
Upvotes: 1
Reputation: 943214
Still }.bind(this), 300)
. ES6 is backwards compatible.
You could also use an arrow function (as you do to define getInitialState
).
Upvotes: 1