Skip to content

Instantly share code, notes, and snippets.

@jurosh
Last active July 14, 2017 14:38
Show Gist options
  • Select an option

  • Save jurosh/5ef25a18ac3f6b21355ca6a4dd719c55 to your computer and use it in GitHub Desktop.

Select an option

Save jurosh/5ef25a18ac3f6b21355ca6a4dd719c55 to your computer and use it in GitHub Desktop.
React map keys issue?
// https://stackoverflow.com/questions/42773892/wrong-components-rendered-by-preact
// https://facebook.github.io/react/docs/lists-and-keys.html
import * as React from 'react';
class Component extends React.Component<any, any> {
constructor() {
super();
this.state = { listing: ['First', 'Second', 'Last'] };
setInterval(() => {
this.setState({ listing: ['First', 'Last'] });
}, 3000);
}
public render() {
return (
<div style={{ color: 'white' }}>
Listing:
{this.state.listing.map((item: string, index: number) =>
<div key={index}>
Item with key {index} is
<span>{item}</span>
</div>
)}
</div>
);
}
}
/*
Results:
Item with key 0 isFirst
Item with key 1 isSecond
Item with key 2 isLast
-- After 3 seconds (correctly changed even when using index)--
Item with key 0 isFirst
Item with key 1 isLast
*/
export default Component;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment