2

In a parent component I am populating a 2D array with a bunch of functional components. However, because I am putting it into an array, each element needs a unique key. What is best practice for doing this with stateless functional components?

var dim = this.props.dim;

    var cells = [];
    for (var i = 0; i < dim; i++) {
      var row = [];
      for (var j = 0; j < dim; j++) {
        row.push(Cell({dim:10, isAlive:this.state.matrix[i][j].isAlive}))
      }
      cells.push(row);
    };
3
  • 1
    I mean, where should I add this property to the sf component? Commented Oct 30, 2017 at 20:48
  • 1
    What do you mean? Please post your React code. Commented Oct 30, 2017 at 20:48
  • 1
    Should I just pass it in as a prop? Commented Oct 30, 2017 at 20:50

4 Answers 4

2

You are not using your functional component (Cell) as a functional component. You aren't suppose to call them like functions. You are supposed to render them using React.

You can use JSX syntax:

var dim = this.props.dim;

var cells = [];
for (var i = 0; i < dim; i++) {
  var row = [];
  for (var j = 0; j < dim; j++) {
    row.push(<Cell key={`${i}-${j}`} dim={10}, isAlive={this.state.matrix[i][j].isAlive> />);
  }
  cells.push(row);
};

Or you can use React API

var dim = this.props.dim;

var cells = [];
for (var i = 0; i < dim; i++) {
  var row = [];
  for (var j = 0; j < dim; j++) {
    row.push(React.createElement(Cell, {key:`${i}-${j}`, dim:10, isAlive:this.state.matrix[i][j].isAlive}, null);
  }
  cells.push(row);
};

Both those forms allow you to pass in the key property and allow React to consume it.

Sign up to request clarification or add additional context in comments.

1 Comment

Cheers mate, exactly what I was looking for.
1

You could add the index of that element, which is given by index = i * dim + j. This way it's unique for all items and consecutive.

Comments

1

here is an example that you should be able to work with:

// parent
const arr = ['i', 'like', 'cats']

const arrWithKeys = arr.map((item, i) => ({ key: i, item }))

console.log(arrWithKeys)

// child
arrWithKeys.forEach((thing) => console.log(`<Something key={${thing.key}} item={${thing.item}} />`))

pass arrWithKeys into the child like this:

<Component arrWithKeys={arrWithKeys} />

and access it inside the component as this.props.arrWithKeys

Comments

0

use jsx syntax only:

 class mat extend Component{  
render(){
    return <div>
     {this.state.matrixCell.map((row, i)=>row.map((col, k)<Cell key={i*dim+k} dim={10} isAlive = {col.isAlive}))}
    </div>;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.