JSX is merely JavaScript and to render a list you can use the array method .map
to map an array to React elements. However, if you don't use the key
prop correctly, it can lead to unexpected results, so we explore what can happen and how to use the key
prop correctly.
Hello,
I'm having problems with this example not recognizing the id portion of the item
{items: Array(6)} Inline Babel script:65 Uncaught TypeError: Cannot read property 'id' of undefined at <anonymous>:93:34 at Array.map (<anonymous>) at App.render (<anonymous>:90:23) at finishClassComponent (react-dom.development.js:11360) at updateClassComponent (react-dom.development.js:11337)
<strong>I cut and pasted the example to get going!</strong>
and the code:
render(){
const {items}= this.state
return(
<div>
<button
onClick={this.addItem}
>
+
</button>
{items.map((i, index) => (
<div key={i.id}>
<button
onClick={() => this.removeItem(i)}
>
-
</button>
{i.value}:
<input />
</div>
))}
</div>
)
}
}
<quote> render(){ const {items}= this.state return( <div> <button onClick={this.addItem} > + </button> {items.map((i, index) => ( <div key={i.id}> <button onClick={() => this.removeItem(i)} > - </button> {i.value}: <input /> </div> ))} </div> ) } }</quote>and the code:
Problem, resolved. I missed the arrow function in the setState function used to copy the arrays items.
Great example... Awesome, Fantastico... Thanks
The input focus example is the best visual I've seen thus far in this course. Great way to drive home the importance of unique identifiers.
Why use App and not the this keyword?
The properties you're talking about I'm assuming are the static properties. You cannot access static properties via this
because they're not instance properties or even prototype properties. That's why I'm referencing App
instead of this
.
Hi Kent, great course, thank you, so, you explained abit about using static, what is the advantage over state?
Hi Rolando,
In retrospect I wish I hadn't don the static
thing because there's been a lot of confusion about it and it really isn't doing much useful. The reason I did it was for the code to communicate that those properties are related in an important way to their "owner."
No worries Kent, thanks for the answer and help :)
Hey Kent,
great course, one doubt about this video, why do we need ({
in setState
. For example,
this.setState(({items}) => ({
items: items.filter(i => i !== item),
}))
Thanks, Lokesh.
Hi Lokesh, That's shorthand for this:
this.setState(previousState => {
return { items: previousState.items.filter(i => i !== item) }
})
If you remove the ({
the syntax will be wrong for the shorthand and your JavaScript wont compile.