Reputation: 33
I have a list of names as an array. These names are then paired, into an array in my App.js
I'm looking to map over these to create a <ul> containing <li>
s and I'm stuck, any help would be amazing, thanks!
Unfortunately regular map over an array like this won't work... Thanks so!
return (
<ul>
{pairs.map(pair => (
<li key={pair}>{pair}</li>
))}
</ul>
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
createPairs() {
const list = [...this.state.list];
list.sort(() => 0.5 - Math.random());
const pairs = [];
while (list.length >= 2) {
const pair = [list.pop(), list.pop()];
pairs.push(pair);
}
this.setState({
pairs
});
}
Upvotes: 2
Views: 62
Reputation: 3711
You can potentially use destructuring within your map
arguments to extract the components of each pair. Remember to wrap the destructured arguments in parentheses.
return (
<ul>
{pairs.map(([pair_1, pair_2]) => (
<li key={pair_1}>{pair_1}</li>
))}
</ul>
);
Upvotes: 2