react keys


#1

I am getting the error Warning: Todo:keyis not a prop. Trying to access it will result inundefinedbeing returned. If you need to access the same value within the child component, you should pass it as a different prop.

For context: https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318

My code (I am very new to React):

import React, {Component} from 'react';
import Todo from './todo.js';
import shortid from 'shortid';

var todosArray = [
	{title: "thingy", description: "some stuff"},
	{title: "blah", description: "other stuff"},
	{title: "go to shop", description: "buy some milk"},
	{title: "study", description: "learn React"}
	]

	todosArray.forEach((todo) => {
	todo.key = shortid.generate()
	})

class Todos extends Component {

	delete(key) {
		todosArray.filter((item) => {
			console.log(item.key)
			return(item.key !== key)
		})
	}

	render() {

		var todos = todosArray.map((todo, index) => {
			return <Todo delete={this.delete} key={todo.key} title={todo.title} description={todo.description}/>
			})
		return(
			<ul className="grid">
				{todos}
			</ul>
		)
	}
}

export default Todos;

#2

Because key is used by React for keeping track of elements, it might be reserved as a prop name. Try renaming key={todo.key} to something like itemKey={todo.key}. Does that work? :slight_smile: