Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial![](https://ecs-static.teamtreehouse.com/assets/views/marketing/shared/community-banner-white-47072046c51352fe6a69f5e691ff5700b28bb11d45197d7bdf066d9ea3f72d0c.webp)
![Seth Foss](https://secure.gravatar.com/avatar/ca4a084cc9b31ae7449178e7ce05b721?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
Seth Foss
7,097 PointsWhy did we need to use a new id prop instead of the existing key prop?
In this lesson, we used passed a handler method to a child component to remove items from state. The handler needed an id parameter so it could remove the correct item. The child item already had a key={props.id}
property, but the lesson added a id={props.id}
and used that when calling the method.
To simplify the code a little, I tried just using the key (props.key
inside the Item component), but that was undefined. Is the key
property of a component not available inside itself, or is there some special way to call it?
Here's the relevant parts of my code:
const App = () => {
const [items, setItems] = useState([
...
])
const handleRemoveItem = (id) => {
console.log("Removing " + id)
setItems(prevItems => prevItems.filter(i => i.id !== id))
}
return (
<div className='grocery-list'>
<Header
title='My Grocery List'
itemTotal={items.length} />
{/*Grocery List */}
{items.map(item =>
<Item
key={item.id}
name={item.name}
removeItem={handleRemoveItem}
/>
)}
</div>
)
}
const Item = (props) => {
return (
<div className="item">
<button className="remove-item" onClick={() => props.removeItem(props.key)}/>
<span className="item-name">{props.name}</span>
<Counter />
</div>
)
}
The output in the console is: Removing undefined
1 Answer
![Jamie Reardon](https://uploads.teamtreehouse.com/production/profile-photos/9708342/micro_treehouse-mod-slack-profile-pic.jpg)
Jamie Reardon
Treehouse Project ReviewerHi @Seth Foss the key prop is not part of the props object for a component, you can visualize this by console logging the props object inside the component to see it's available properties within the object. Therefore, this results in undefined and why another prop is used when associating items.
Seth Foss
7,097 PointsSeth Foss
7,097 PointsOk, that matches what I observed. Is it known why React was designed so the "key" is set like a prop, but isn't treated like one?