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

JavaScript React Basics Understanding State Remove Items from State

Seth Foss
Seth Foss
7,097 Points

Why 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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jamie Reardon
Treehouse Project Reviewer

Hi @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.

Resource

Seth Foss
Seth Foss
7,097 Points

Ok, 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?