Reputation: 43
I am learning react.js. I am trying to execute a code in VS code based on setState. I have created a button. When I will click on it, the age value will change. But the button is not working. Can you please help me what is the error in the following code?
import React, { Component } from 'react'
class Pain extends Component {
constructor() {
super()
this.state = {
age: '28'
}
}
changeName(a) {
this.setState = { age: a }
}
render() {
return (
<div>
<h1>{this.state.age}</h1>
<button onClick={this.changeName.bind(this, '30')}>Change Name</button>
</div>
)
}
}
export default Pain
Upvotes: 0
Views: 86
Reputation: 9928
It's simply the wrong syntax in this.setState
, here's the better code. Another thing could be you should use ES6 arrow function syntax instead of manually using bind
for better readable.
import React, { Component } from 'react'
class Pain extends Component {
constructor() {
super()
this.state = {
age: '28'
}
}
changeName = (a) => {
this.setState({ age: a })
}
render() {
return (
<div>
<h1>{this.state.age}</h1>
<button onClick={() => this.changeName('30')}>Change Name</button>
</div>
)
}
}
export default Pain
Upvotes: 1
Reputation: 683
import React, {Component} from 'react'
class Pain extends Component {
constructor(){
super()
this.state = {
age: "28"
}
}
changeName = age => {
this.setState({...this.state, age})
}
render(){
return(
<div>
<h1>{this.state.age}</h1>
<button onClick={() => this.changeName("30")}>Change Name</button>
</div>
)
}
}
export default Pain
Upvotes: 1