I have problem here with this.greet() is undefined i have to bind onlick event dirrently to work, any ideas how to fix it ?
import React from 'react';
export default class Example1 extends React.Component {
constructor() {
super();
this.message = {
greeting: 'Hello',
name: 'World',
};
}
greet() {
const { greeting, name } = this.message;
console.log(`${greeting} ${name}!`);
}
onClick() {
try {
this.greet();
} catch (e) {
console.error('Why have I failed? Can you fix me?');
}
}
render() {
return (
<div>
<button onClick={this.onClick}>Greet the world</button>
</div>
);
}
}
i have tried many other ways but it didnt work out anyway.
if you want have "this" in your class component you should add props inside constructor invocation and also into the super
constructor(props) {
super(props);
this.greet = this.greet.bind(this) // need's to be bounded
}
Problem is this keyword.
This is because of the way this works in javascript.
thisloses it's context when it gets used in callbacks.
There are two solutions for this problem. But I would recommend the arrow function solution the most.
Bind this in the onClick callback.
onClick() {
try {
this.greet();
} catch (e) {
console.error('Why have I failed? Can you fix me?');
}
}
render() {
return (
<div>
<button onClick={this.onClick.bind(this)}>Greet the world</button>
</div>
);
}
Use arrow functions for defining callbacks, ( personally recommended )
onClick = () => {
try {
this.greet();
} catch (e) {
console.error('Why have I failed? Can you fix me?');
}
}
render() {
return (
<div>
<button onClick={this.onClick}>Greet the world</button>
</div>
);
}
You lost this reference, you have to bind your functions:
<button onClick={this.onClick.bind(this)}>Greet the world</button>
or pass an arrow function
<button onClick={() => this.onClick()}>Greet the world</button>