I am new to React hooks and been playing with the useState function lately.. In vanilla javascript this code works:
const state = {
firstname: "John",
lastname: "Doe",
greeting: function(){
return sayHello(this.firstname,this.lastname)
}
}
const sayHello = (fname,lname)=>{
return `Hello i'm ${fname} ${lname}, nice to meet you!`;
}
console.log(state.greeting()); //outputs "Hello i'm John Doe, nice to meet you!"
But with React hooks:
const [state,setState] = useState({
firstName: "John",
lastName: "Doe",
greeting: function(){
return sayHello(this.firstName,this.lastName)
}
})
const sayHello = (fname,lname) => console.log(`Hello i'm ${fname} ${lname}, nice to meet you!`);
const { firstName, lastName, greeting } = state;
return (
<div>
<button className="btn" onClick={greeting()}>Greet</button>
</div>
)
I get an error saying: "Cannot read property 'firstName' of undefined", and i also get [object object] if i just use the "firstName" and "lastName" within the method without the "this" keyword. How can i access the variables?