Tell us what’s happening:
So I tried and it passes the test if I define the handleClick() method with an arrow function, but is there something wrong with it and should I keep it to the standard way - the normal ES6 way of defining a function?
**Your code so far**
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'Initial State'
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() { // can this be handleClick = () => {}
// Change code below this line
// Change code above this line
}
render() {
return (
<div>
<button onClick={this.handleClick}>Click Me</button>
<h1>{this.state.name}</h1>
</div>
);
}
};
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36
There shouldn’t be problem with that. Try to replace the same with an arrow function and see. It still works!
Arrow functions are just an ES6 concise way of defining functions.
class MyComponent extends React.Component
state = {
name: 'Initial State'
};
handleClick = () => {
// Change code below this line
// Change code above this line
};
render() {
return (
<div>
<button onClick={this.handleClick}>Click Me</button>
<h1>{this.state.name}</h1>
</div>
);
}
};
The assignment is important here
class Example {
state = { name: "Initial state" };
handleClick = () => { /* do something */ }
....
}
You’re saying "when an object is created by instantiating this class, assign { name: "Initial state" } to this.state and assign the anonymous function () => { // whatever handleClick does to this.handleClick"
For completeness, this is normally how it’s done at this point in time:
const MyComponent = () => {
// Or `function MyComponent() {`
const [name, setName] = React.useState("Initial state")
const handleClick = () => {
// Change code below this line
// Change code above this line
}
return (
<div>
<button onClick={handleClick}>Click Me</button>
<h1>{name}</h1>
</div>
)
}