gavenkoa
gavenkoa

Reputation: 48753

React: should I add key to DOM or it is enough to keep it in object state?

For performance reason and to avoid Warning: Each child in an array or iterator should have a unique "key" prop key should be added to state.

It is unclear if key attribute should be added to DOM. For example should I add key to React.createElement('li', {className: 'book'}, in:

var books = [
    {key: 1, author: "aaa", title: "111"},
];

var BookView = createReactClass({
    render: function() {
        return React.createElement('li', {className: 'book'},
            this.props.author,
            " - ",
            React.createElement('i', null, this.props.title))
    },
});
var BooksView = createReactClass({
    render: function () {
        return React.createElement('ul', {className: 'books'},
            this.props.data.map(function(__) { return React.createElement(BookView, __); }))
    }
});

var booksArea = document.getElementById('booksArea');
ReactDOM.render(React.createElement(BooksView, {data: books}), booksArea);

Upvotes: 0

Views: 50

Answers (2)

Aaqib
Aaqib

Reputation: 10350

As descirbed in React Documentation :

A good rule of thumb is that elements inside the map() call need keys.

So in your case its BooksView as you are creating a lists of elements using .map()

As you are already passing key property as a props to the model , that would be sufficient to satisfy the warning.

Upvotes: 2

Richard Szalay
Richard Szalay

Reputation: 84734

You need to pass a key prop to the repeated element. In this case, BookView.

Since your model already has a key property, and you are passing that model as the props object, that should be sufficient.

Upvotes: 1

Related Questions