2
votes

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

2
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 has already been answered a lot on SO.Emile Bergeron

2 Answers

5
votes

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'
})
3
votes

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.