Reputation: 309
I have a div where the name should be displayed by pressing a button. The two buttons below, if you click on the first, the John name should appear, and if the second, Donald. Where is the mistake?
import React, { Component } from 'react';
class trueName extends Component {
constructor(props) {
this.state = {
name: {},
};
}
john = ()=>{
const {name}= this.state;
this.setState({name:"John"})
}
donald = ()=>{
const {name}= this.state;
this.setState({name:"Donald"})
}
render() {
return(
<div >
<div className="SelectName">
<span>{this.name}</span>
</div>
<button
className = "one"
onClick={ this.john}>
<span>My name John</span>
</button>
<button
className = "two"
onClick={ this.donald}
>
<span>My name Donald</span>
</button>
</div>
)
}
}
export default trueName;
Upvotes: 0
Views: 41
Reputation: 36
As other people have mentioned, you need to set the value to a string.
But also, whne you are displaying the value, you have an error. You are looking for this.name
while what you want to display is this.state.name
Upvotes: 2
Reputation: 1047
You need to use '
, "
or ``` to make the value of name a string:
this.setState({name:'John'})
/// ...
this.setState({name:'Donald'})
also only constructors should be written with an uppercase letter at the beginning, not methods, rename the function John
to john
.
Upvotes: 0