Uncaught TypeError: this is undefined

Viewed 30

This react component:

import React, { Component } from 'react';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userName: "Adam"
    }
  }

  changeStateData() {
    this.setState({
      userName: this.state.userName === "Adam" ? "Bob" : "Adam"
    });
  }

  render() {
    return (
      <div>
        <h4 className='bg-primary text-white text-center p-2'>
          {this.state.userName}'s To Do List
        </h4>
        <input
          type="button"
          className='btn btn-primary m-2'
          onClick={this.changeStateData}
          value="Change"
        >
        </input>
      </div>
    )
  }
}

Is giving me in the console this error:

Uncaught TypeError: this is undefined
    changeStateData app.js:12
    React 5
    processDispatchQueueItemsInOrder bundle.js:16352
    React 5
    dispatchEventForPluginEventSystem bundle.js:16567
    dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay bundle.js:13743
    React 2

Why? It is method inside class, so it should have available this scope right?

0 Answers
Related