I have a react component that works without arrow functions (commented out below), but I would love being able to use arrow functions instead of binding each function by hand.
This (the not commented out part) is what I tried:
import React from 'react'
export default class CowClicker extends React.Component {
constructor(props) {
super(props)
this.state = {
clicks: 0
}
// this.onCowClick = this.onCowClick.bind(this)
// that makes it work if I use a normal function instead of a fat arrow one for onCowClick
}
// alternative that works: onCowClick(evt) {...}
onCowClick = (evt) => {
this.setState({
clicks: this.state.clicks + 1
})
}
render() {
return (
<div>
<div>Clicks: {this.state.clicks}</div>
<img
src="http://s3.bypaulshen.com/buildwithreact/cow.png"
onClick={this.onCowClick}
className="cow"
/>
<p>Click the cow</p>
</div>
)
}
}
How can I enable the use of arrow functions in my project ?
This link seems to be part of the solution, but as a front-end newbie I fail to know how to apply it.
Also, as a side question, how do you know what is wrong in a jsx file ? What are good tools to troubleshoot react code ? I picked brunch as a build system because it seemed the simplest to get started with front-end, and the only error it gives me is Compiling of app/components/CowClicker.jsx failed.
For more context :
- my app is set up using
brunch new -s react
, which puts a react app skeleton in place - I'm using vscode as a text editor if you have any linting / compilation error spotting extensions to recommend, I would definitely appreciate
- My build config (I build with brunch) looks like this (it's the default one with the 'react' skeleton of brunch) :
.
module.exports = {
files: {
javascripts: {
joinTo: {
'vendor.js': /^(?!app)/,
'app.js': /^app/
}
},
stylesheets: {joinTo: 'app.css'}
},
plugins: {
babel: {presets: ['es2015', 'react']}
}
};