Gazi Md. Yeasin
Gazi Md. Yeasin

Reputation: 43

What is the problem with this reactjs setState function code?

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

Answers (3)

Ahmed Gamal Mustafa
Ahmed Gamal Mustafa

Reputation: 29

Just remove the = in setState.

this.setState({age: a})

Upvotes: 1

Loi Nguyen Huynh
Loi Nguyen Huynh

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

Afia
Afia

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

Related Questions