ivankoleda
ivankoleda

Reputation: 350

warning on creating multiple elements using React.createElement

I use React.createElement to create elements with dynamic view:

{list && list.length !== 0 ?
    list.map((model, i) =>
        React.createElement(ListRow, {
            key: i,
            model,
            ...rowProps,

            onEdit: () => this.onEdit(model),
            onDelete: () => this.onDelete(model)
    })) : null
}

This works fine for me, but I get this warning in console:

Warning: Each child in an array or iterator should have a unique "key" prop. See *here shold be link* for more information.
    in EditableList (created by Connect(EditableList))
    in Connect(EditableList) (created by CreateInvoiceFormView)

I get this warning even if list.length === 0< and have no idea why this happens. I've tried to generate id's, that didn't help.

Here is whole component code:

class EditableList extends Component {
componentWillMount() {
    const {name, dispatch} = this.props;
    dispatch(createList(name));
}

componentWillUnmount() {
    const {name, dispatch} = this.props;
    dispatch(destroyList(name));
}

onAdd(item) {
    const {dispatch, name} = this.props;
    dispatch(openPopup(name, item));
}

onEdit(item) {
    const {dispatch, name} = this.props;
    dispatch(editItem(name, item));
    dispatch(openPopup(name, item));
}

onDelete(item) {
    const {dispatch, name} = this.props;
    dispatch(deleteItem(name, item));
}

render() {
    const {ListRow, list, rowProps, title} = this.props;

    return [
        <SectionTitleView title={title} add onClick={() => this.onAdd()}/>,
        <div>{list && list.length !== 0 ? list.map((model, i) =>
            React.createElement(ListRow, {
                key: i,
                model,
                ...rowProps,

                onEdit: () => this.onEdit(model),
                onDelete: () => this.onDelete(model)
            })) : null
        }
        </div>];
}
}

I searched for this problem in here on stack by couldn't fing anything similar, and I have no idea what am I doing wrong. Please let me know, if I don't provide enough information for this issue.

Upvotes: 0

Views: 847

Answers (1)

Minkesh Jain
Minkesh Jain

Reputation: 1160

You are using latest syntax of react v16.0, It requires you to add keys to all the elements. Since your SectionTitleView element does not have the key attribute you are getting this error.

For more details please refer: https://reactjs.org/blog/2017/09/26/react-v16.0.html#new-render-return-types-fragments-and-strings

Alternatively, you can also wrap your components inside a <div> in the render function.

Upvotes: 1

Related Questions