Home » Reactjs » React, ES6 – getInitialState was defined on a plain JavaScript class

React, ES6 – getInitialState was defined on a plain JavaScript class

Posted by: admin November 29, 2017 Leave a comment

Questions:

I have the following component (radioOther.jsx):

 'use strict';

 //module.exports = <-- omitted in update

   class RadioOther extends React.Component {

     // omitted in update 
     // getInitialState() {
     //    propTypes: {
     //        name: React.PropTypes.string.isRequired
     //    }
     //    return {
     //       otherChecked: false
     //   }
     // }

     componentDidUpdate(prevProps, prevState) {
         var otherRadBtn = this.refs.otherRadBtn.getDOMNode();

         if (prevState.otherChecked !== otherRadBtn.checked) {
             console.log('Other radio btn clicked.')
             this.setState({
                 otherChecked: otherRadBtn.checked,
             });
         }
     }

     onRadChange(e) {
         var input = e.target;
         this.setState({
             otherChecked: input.checked
         });
     }

     render() {
         return (
             <div>
                 <p className="form-group radio">
                     <label>
                         <input type="radio"
                                ref="otherRadBtn"
                                onChange={this.onRadChange}
                                name={this.props.name}
                                value="other"/>
                         Other
                     </label>
                     {this.state.otherChecked ?
                         (<label className="form-inline">
                             Please Specify:
                             <input
                                 placeholder="Please Specify"
                                 type="text"
                                 name="referrer_other"
                                 />
                         </label>)
                         :
                         ('')
                     }
                 </p>
             </div>
         )
     }
 };

Prior to using ECMAScript6 all was well, now I am getting 1 error, 1 warning and I have a followup question:

Error: Uncaught TypeError: Cannot read property ‘otherChecked’ of null

Warning: getInitialState was defined on RadioOther, a plain JavaScript class. This is only supported for classes created using
React.createClass. Did you mean to define a state property instead?


  1. Can anyone see where the error lies, I know it is due to the conditional statement in the DOM but apparently I am not declaring its initial value correctly?

  2. Should I make getInitialState static

  3. Where is the appropriate place to declare my proptypes if getInitialState is not correct?

UPDATE:

   RadioOther.propTypes = {
       name: React.PropTypes.string,
       other: React.PropTypes.bool,
       options: React.PropTypes.array }

   module.exports = RadioOther;

@ssorallen, this code :

     constructor(props) {
         this.state = {
             otherChecked: false,
         };
     }

produces "Uncaught ReferenceError: this is not defined", and while below corrects that

     constructor(props) {
     super(props);
         this.state = {
             otherChecked: false,
         };
     }

but now, clicking the other button now produces error:

Uncaught TypeError: Cannot read property 'props' of undefined

Answers:
  • getInitialState is not used in ES6 classes. Instead assign this.state in the constructor.
  • propTypes should be a static class variable or assigned to the class, it should not be assigned to component instances.
  • Member methods are not “auto-bound” in ES6 classes. For methods used as callbacks, either use class property initializers or assign bound instances in the constructor.
export default class RadioOther extends React.Component {

  static propTypes = {
    name: React.PropTypes.string.isRequired,
  };

  constructor(props) {
    super(props);
    this.state = {
      otherChecked: false,
    };
  }

  // Class property initializer. `this` will be the instance when
  // the function is called.
  onRadChange = () => {
    ...
  };

  ...

}

See more in the React’s documentation about ES6 Classes: https://facebook.github.io/react/docs/state-and-lifecycle.html#converting-a-function-to-a-class

Questions:
Answers:

Adding to Ross’s answer.

You could also use the new ES6 arrow function on the onChange property

It is functionally equivalent to defining this.onRadChange = this.onRadChange.bind(this); in the constructor but is more concise in my opinion.

In your case the the radio button will look like the below.

<input type="radio"
       ref="otherRadBtn"
       onChange={(e)=> this.onRadChange(e)}
       name={this.props.name}
       value="other"/>

Update

This “more concise” method is less efficient than the options mentioned in @Ross Allen’s answer because it generates a new function each time the render() method is called

Questions:
Answers:

If you are using babel-plugin-transform-class-properties or babel-preset-stage-2 (or stage-1, or stage-0), you can use this syntax:

class RadioOther extends React.Component {

  static propTypes = {
    name: React.PropTypes.string,
    ...
  };

  state = {
      otherChecked: false,
  };

  onRadChange = () => {
    ...
  };

  ...

}