Skip to content

Instantly share code, notes, and snippets.

@djsmith42
Last active August 29, 2015 14:20
Show Gist options
  • Save djsmith42/46aece60e3c07284dab3 to your computer and use it in GitHub Desktop.
Save djsmith42/46aece60e3c07284dab3 to your computer and use it in GitHub Desktop.
/*
* 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>
)
}
}
@marduke182
Copy link

See this: http://stackoverflow.com/a/28993564/1121547

Solution: change key={index} to key={thing.name} (Or some unique value)

@gaearon
Copy link

gaearon commented May 7, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment