Ad

React TextArea Component - How To Use GetInititalState() In ES6?

- 1 answer

I have a relatively simple snippet, that's been written in JSX/ES6.

import React from 'react'

class TextArea extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <textarea defaultValue={this.props.text}></textarea>
        <h3>{this.props.text.length}</h3>
      </div>
    )
  }
}

TextArea.propTypes = {
  text: React.PropTypes.string
}


export default TextArea;

Since this class was not generated with React.createClass, attempting to add getInitialState results in a big red console warning:

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

How does one properly use the getInitialState() in an ES6 class?

Ad

Answer

In class constructor need set state property

constructor(props) {
  super(props);
  this.state = {  }
}

Example

Ad
source: stackoverflow.com
Ad