how to break a .map function? Code samples attached below. I want to break the look once the index reached at 5 because I only want to render 5 Avatar to the screen.
<View style={{ flexDirection: 'row', marginTop: 20, marginLeft: 30 }}>
{
peopleGroup.map((people, i) => {
if(i<5) {
return (
<Avatar
key={people.id}
width={30}
position='absolute'
containerStyle={{ transform: [{translate: [-28 + (28 * i), 0, 1 - (i * 0.1)]}] }}
small
rounded
source={{uri: people.image}}
activeOpacity={0.7}
/>
)
}else if(i===5) {
return (
<View key={i} style={{ transform: [{translate: [(25 * i), 9, 0]}] }}>
<Text>{peopleGroup.length}</Text>
</View>
)
}
}
)
}
</View>
To break a map() loop in React: Call the slice() method on the array to get a portion of the array. Call the map() method on the portion of the array. Iterate over the portion of the array.
Not possible, We can't break #array. map, it will run for each element of array.
Double tap the Home button, tap & hold the Maps app until it starts to wiggle, tap the red minus sign. Fantastic.
Use Array.slice
before you map.
peopleGroup
.slice(0, 5) // creates a copy of original, 5 items long
.map(...) // subsequent operations work on the copy
Tada!
instead of using .slice
and .map
which will create another loop.
You can use .reduce
, that way you are doing your logic with one loop (better performance).
The difference is that .map
will have to return the same length of the array, where .reduce
can return anything actually.
data.reduce((result, current, i) => {
if (i < 5) {
result.push(<div>{current}</div>);
}
return result;
}, [])
Running example:
const data = [1, 2, 3, 4, 5, 6, 7];
const App = () => (
<div>
{data.reduce((result, current, i) => {
if (i < 5) {
result.push(<div>{current}</div>);
}
return result;
}, [])}
</div>
);
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
How to break a .map function?
Not possible, We can't break #array.map, it will run for each element of array.
To solve your problem, you can use slice first then map, slice first 5 elements of array then run map on that.
Like this:
peopleGroup.slice(0,5).map((people, i) => {
return (...)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With