Ad

Warning: GetInitialState Was Defined On DimensionPicker, A Plain JavaScript Class. This Is Only Supported For Classes Created Using React.createClass

- 1 answer

I am trying to write my first react control. Here is what I have written

import React from 'react';
import DimensionPickerAction from '../actions/DimensionPickerActions.js';
import MovieLensAppStore from '../stores/MovieLensAppStore.js';

class DimensionPicker extends React.Component {

    constructor(props) {
        super(props);
        this.state = { items: [], currentItem: '' };
    }

    getInitialState() {
        this.state = {
            items: MovieLensAppStore.getAttributes(this.props.dimension),
            currentItem : MovieLensAppStore.getCurrentAttribute(this.props.dimension)
        };
    }

    onSelectionChange(newValue) {
        DimensionPickerAction.selectionChange(this.props.dimension, newValue);
    }

    render() {
        var optionNodes = this.state.items.map((item) => {
            if (item === this.state.currentItem) 
                return(<option value="{item}" selected>{item}</option>)             
            else
                return(<option value="{item}">{item}</option>)
        });
        return(<div><select onchange="onSelectionChange">{optionNodes}</select></div>);
    }

}

export default DimensionPicker;

Very surprisingly, I get an error

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

I find this very confusing because clearly my component derives from React.Component

Ad

Answer

Eric's comment is correct. You're using ES6 classes, which means that getInitialState is not supported. You'll need to change this:

class DimensionPicker extends React.Component {

    constructor(props) {
        super(props);
        this.state = { items: [], currentItem: '' };
    }

    getInitialState() {
        this.state = {
            items: MovieLensAppStore.getAttributes(this.props.dimension),
            currentItem : MovieLensAppStore.getCurrentAttribute(this.props.dimension)
        };
    }

to this:

class DimensionPicker extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            items: MovieLensAppStore.getAttributes(props.dimension),
            currentItem : MovieLensAppStore.getCurrentAttribute(props.dimension)
        };
    }
Ad
source: stackoverflow.com
Ad