Last active
July 16, 2017 18:18
-
-
Save dzek69/1c923d0405619de805520cd0c2fa363f to your computer and use it in GitHub Desktop.
React keys
This file contains hidden or 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
const React = require("react"); | |
const { render } = require("react-dom"); | |
const root = document.querySelector("#r"); | |
const itemA = { | |
key: "A", | |
name: "Item A", | |
}; | |
const itemB = { | |
key: "B", | |
name: "Item B", | |
}; | |
const itemC = { | |
key: "C", | |
name: "Item C", | |
}; | |
const itemD = { | |
key: "D", | |
name: "Item D", | |
}; | |
const items = [ | |
[itemA, itemB, itemC], | |
[itemC, itemB, itemD], | |
]; | |
class App extends React.Component { | |
constructor(props, context) { | |
super(props, context); | |
this.state = { | |
index: 0, | |
items: items[0], | |
} | |
this.switchItems = this.switchItems.bind(this); | |
} | |
switchItems() { | |
const nextIndex = this.state.index ? 0 : 1; | |
this.setState({ | |
index: nextIndex, | |
items: items[nextIndex], | |
}) | |
} | |
render() { | |
const items = this.state.items.map(item => { | |
return <li key={item.key}>{item.name}</li> | |
}) | |
return ( | |
<div style={{padding: "20px"}}> | |
{items} | |
<hr /> | |
<button onClick={this.switchItems}>Switch now</button> | |
</div> | |
) | |
} | |
} | |
render(<App />, root) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment