0

I am working, as an exercise, in converting a very, very simple video game from a jQuery (re)implementation to what I would like to be idiomatic ReactJS. I am (trying to) use the React tutorial as my reference.

The jQuery reimplementation stores the state as an array of arrays of characters. I am presently trying to get initial state to be rendered in ReactJS. Originally I set the getInitialState() to return the data (an array of arrays) originally returned. That didn't work, as ReactJS seems to want an object and not an array (React.js: arrays and "Critical assumptions about the merge functions have been violated" error).

The tutorial, in the "Tutorial 10" section, uses Array.map(), suggesting that some level of containing Arrays might be helpful:

Now that the data is available in the CommentList, let's render the comments dynamically:

// tutorial10.js
var CommentList = React.createClass({
  render: function() {
    var commentNodes = this.props.data.map(function (comment) {
      return (
        <Comment author={comment.author}>
          {comment.text}
        </Comment>
      );
    });
    return (
      <div className="commentList">
        {commentNodes}
      </div>
    );
  }
});

What is the best way to translate a grid of characters (presently implemented as an array of arrays)? Do I put the array as a node on this.state (the state is subject to change, so I am setting state rather than props) and then an Array.map() (or something two-dimensional)?

Community
  • 1
  • 1
Christos Hayward
  • 5,777
  • 17
  • 58
  • 113

2 Answers2

1

What is the idiomatic ReactJS way to deal with ?initial? state?

Ideally, default data is passed as prop(s) to the root component. E.g.

React.render(
  <MyApp gid={grid} />,
  container
);

However, simply returning it form the getInitialState method is fine as well.

Originally I set the getInitialState() to return the data (an array of arrays) originally returned. That didn't work, as ReactJS seems to want an object and not an array

Just make your data one aspect of the state:

getInitialState() {
  return {
    grid:  this.props.grid
  };
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

If you're using ES2015 synax you can you initialize state directly in constructor function:

constructor() {
  super();
  this.state = {...}
 }
Bartek Fryzowicz
  • 6,464
  • 18
  • 27