2

import React, { Component } from 'react'

class Columns extends Component{ constructor(props){ super(props)

    this.state={
        message:'Hello'
    }
}

changeMessage(){
    
     this.setState=({
         message:'Welcome'
    })
}

render(){
    return(
        <div>
            <div>{this.state.message}</div>
            <button onClick={this.changeMessage}>Click</button>
        </div>
    )
}

} export default Columns

Simran Mhaske
  • 65
  • 1
  • 5
  • Both answers you received are right, though none of them is really necessary as `this.setState = ...` is a typo-like problem and the [`this` problem](https://stackoverflow.com/q/33973648/1218980) has already been [answered](https://stackoverflow.com/q/3127429/1218980) a [lot](https://stackoverflow.com/q/20279484/1218980) on SO. – Emile Bergeron Jul 30 '20 at 19:19

2 Answers2

5

As ray hatfield said above, you're losing the this context and need to use an arrow function, but also you're not calling setState; you're overriding it.

Remove the = from

this.setState=({
     message:'Welcome'
})

so that it says:

this.setState({
    message:'Welcome'
})
Aaron
  • 2,049
  • 4
  • 28
  • 35
3

Because passing it as this.changeMessage detaches it from the component scope. When the button invokes it, "this" is no longer the component.

Change it to an arrow function: () => this.changeMessage()

I've tried to explain this scope issue in another answer in the past if you want the details.

Also, as Aaron points out you also have an extraneous = in your changeMessage handler.

ray
  • 26,557
  • 5
  • 28
  • 27