Last active
August 29, 2015 14:20
-
-
Save djsmith42/46aece60e3c07284dab3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Your challenge: Find the bug in this code. | |
* | |
* The symptom: When I click "Remove" on "Bob", "Fred" disappears. Why? | |
* | |
* Hint: It's not a syntax error, and there are no console warnings. | |
*/ | |
class MyComponent extends React.Component { | |
constructor() { | |
this.state = { | |
things: [{ | |
name: "Bob" | |
},{ | |
name: "Jane" | |
},{ | |
name: "Fred" | |
}] | |
} | |
} | |
remove(index) { | |
this.state.things.splice(index, 1); | |
this.setState({ | |
things: this.state.things | |
}) | |
} | |
render() { | |
return ( | |
<ul> | |
{this.state.things.map((thing, index) => ( | |
<li key={index}> | |
<input type="text" defaultValue={thing.name} /> | |
<button onClick={this.remove.bind(this, index)}>Remove</button> | |
</li> | |
))} | |
</ul> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See this: http://stackoverflow.com/a/28993564/1121547
Solution: change key={index} to key={thing.name} (Or some unique value)