[javascript] React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined

I'm getting this error Uncaught TypeError: Cannot read property 'state' of undefined whenever I type anything in the input box of AuthorForm. I'm using React with ES7.

The error occurs on 3rd line of setAuthorState function in ManageAuthorPage. Regardless of that line of code even if I put a console.log(this.state.author) in setAuthorState, it will stop at the console.log and call out the error.

Can't find similar issue for someone else over the internet.

Here is the ManageAuthorPage code:

import React, { Component } from 'react';
import AuthorForm from './authorForm';

class ManageAuthorPage extends Component {
  state = {
    author: { id: '', firstName: '', lastName: '' }
  };

  setAuthorState(event) {
    let field = event.target.name;
    let value = event.target.value;
    this.state.author[field] = value;
    return this.setState({author: this.state.author});
  };

  render() {
    return (
      <AuthorForm
        author={this.state.author}
        onChange={this.setAuthorState}
      />
    );
  }
}

export default ManageAuthorPage 

And here is the AuthorForm code:

import React, { Component } from 'react';

class AuthorForm extends Component {
  render() {
    return (
      <form>
                <h1>Manage Author</h1>
        <label htmlFor="firstName">First Name</label>
                <input type="text"
                    name="firstName"
          className="form-control"
                    placeholder="First Name"
          ref="firstName"
          onChange={this.props.onChange}
                    value={this.props.author.firstName}
          />
        <br />

        <label htmlFor="lastName">Last Name</label>
                <input type="text"
                    name="lastName"
          className="form-control"
                    placeholder="Last Name"
          ref="lastName"
                    onChange={this.props.onChange}
          value={this.props.author.lastName}
                    />

                <input type="submit" value="Save" className="btn btn-default" />
            </form>
    );
  }
}

export default AuthorForm

The answer is


Make sure you're calling super() as the first thing in your constructor.

You should set this for setAuthorState method

class ManageAuthorPage extends Component {

  state = {
    author: { id: '', firstName: '', lastName: '' }
  };

  constructor(props) {
    super(props);
    this.handleAuthorChange = this.handleAuthorChange.bind(this);
  } 

  handleAuthorChange(event) {
    let {name: fieldName, value} = event.target;

    this.setState({
      [fieldName]: value
    });
  };

  render() {
    return (
      <AuthorForm
        author={this.state.author}
        onChange={this.handleAuthorChange}
      />
    );
  }
}

Another alternative based on arrow function:

class ManageAuthorPage extends Component {

  state = {
    author: { id: '', firstName: '', lastName: '' }
  };

  handleAuthorChange = (event) => {
    const {name: fieldName, value} = event.target;

    this.setState({
      [fieldName]: value
    });
  };

  render() {
    return (
      <AuthorForm
        author={this.state.author}
        onChange={this.handleAuthorChange}
      />
    );
  }
}

You have to bind your event handlers to correct context (this):

onChange={this.setAuthorState.bind(this)}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to ecmascript-6

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 where is create-react-app webpack config and files? Can (a== 1 && a ==2 && a==3) ever evaluate to true? How do I fix "Expected to return a value at the end of arrow function" warning? Enums in Javascript with ES6 Home does not contain an export named Home How to scroll to an element? How to update nested state properties in React eslint: error Parsing error: The keyword 'const' is reserved Node.js ES6 classes with require

Examples related to ecmascript-7

React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined How to iterate (keys, values) in JavaScript? How can I clone a JavaScript object except for one key? Using `window.location.hash.includes` throws “Object doesn't support property or method 'includes'” in IE11

Examples related to react-state

What is useState() in React? React js change child component's state from parent component React - how to pass state to another component How do I access store state in React Redux? Understanding React-Redux and mapStateToProps() React - changing an uncontrolled input React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined react change class name on state change Clearing state es6 React Updating state on props change in React Form