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

1
  • 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. Commented Jul 30, 2020 at 19:19

2 Answers 2

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' }) 
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.