Skip to content

Instantly share code, notes, and snippets.

@rudin
Last active November 23, 2016 10:11
Show Gist options
  • Save rudin/e6de1261f77c42f951d034f980608e2d to your computer and use it in GitHub Desktop.
Save rudin/e6de1261f77c42f951d034f980608e2d to your computer and use it in GitHub Desktop.
Iterating the react way...
// Like this:
const Item = ({value}) => <li>{value}</li>;
const Iteration = ({data}) => (
<ul>
{data.map((value, index) => <Item key={index} value={value}/>)}
</ul>
);
ReactDOM.render(<Iteration data={[1,2,3,4]}/>, document.getElementById('array'));
// If you like fewer lines:
const Iteration = ({data}) => (
<ul>{data.map((value, index) => <li key={index}>{value}</li>)}</ul>
);
ReactDOM.render(<Iteration data={[1,2,3,4]}/>, document.getElementById('array'));
// Or even better, my current preference: with styled-components:
const Item = styled.li`
text-decoration: line-through;
`;
const List = styled.ul`
line-height: 2em;
`;
const Iteration = ({data}) => (
<List>
{data.map((value, index) => <Item key={index} value={value}/>)}
</List>
);
ReactDOM.render(<Iteration data={[1,2,3,4]}/>, document.getElementById('array'));
// ...and preferably not like this, as mentioned at https://rlafranchi.github.io/2016/05/03/vue-vs-react/
// Will this even work? The render function doesn't return a single element...
var Iteration = React.createClass({
getInitialState() {
return {
array: [1,2,3,4]
}
},
render() {
this.state.array.map( function(value) {
return (
<span>{value}</span>
)
});
}
});
ReactDOM.render(<Iteration />, document.getElementById('array'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment