I'm using create-react-app and attempting to modify the App.js file to have a button that has an onclick method that makes an axios HTTP request. I have been trying this for a couple weeks and the error I've gotten the most has been unexpected token in my handleClick(e). I tried this and I don't understand why it won't compile:
// Example React.js Component
var ButtonComponent = React.createClass({
getInitialState: function() {
return {
numClicks: 0
}
}
click: function() {
this.setState(numClicks: this.state.numClicks + 1);
},
render: function() {
return (
<div>
<button onClick={this.click.bind(this)}>Click Me</button>
{this.state.numClicks}
</div>
);
}
});
If anyone could provide some help I would really appreciate it. I just want to be able to render components that can make requests to my express app.
You're using a deprecated syntax, use instead React with ES6.
And about your problem you have multiple syntax errors:
getInitialState
closing brace.this.setState()
Here's the code with the corrections:
var ButtonComponent = React.createClass({
getInitialState: function() {
return {
numClicks: 0
}
},
click: function() {
this.setState({ numClicks: this.state.numClicks + 1 });
},
render: function() {
return (
<div>
<button onClick={this.click.bind(this)}>Click Me</button>
{this.state.numClicks}
</div>
);
}
});
I would recommend you read the documentation/guide and switch to ES6.
Here's the code also with ES6:
import React, { Component } from 'react';
class ButtonComponent extends Component {
constructor(props) {
super(props);
this.state = {
numClicks: 0
}
}
click() {
this.setState({ numClicks: this.state.numClicks + 1 });
}
render() {
return (
<div>
<button onClick={this.click.bind(this)}>Click Me</button>
{this.state.numClicks}
</div>
);
}
}