Reputation: 8506
Below is my sample code .....
<ul>
{this.state.showAllUser == false
? someArray.slice(0, 3).map(function(user, index) {
return (
<li key={index}> {user.name}<li>
)
: someArray.map(function(user, index) {
return (
<li key={index}> {user.name}<li>
)
}
</ul>
If this.state.showAllUser is false, i will only show three of array or show all of them if true.
My question is how to make this code more clean , can I make a function or variable and use it in refer function?
Upvotes: 0
Views: 46
Reputation: 3003
You could use the Array method instead, like so:
<ul>
{someArray.filter(function(el, index) {
if (!this.state.showAllUser) {
// Print the first 3 elements
return (index < 3)
} else {
// Print all
return true
}
})
.map(function(user, index) {
return (<li key={index}> {user.name}</li>)
})
}
</ul>
In this way it is very clear where you control which elements are going to be shown and which are not.
And more you write only once the virtual DOM part.
Upvotes: 1
Reputation: 305
<ul>
{
(this.state.showAllUser == false ? someArray.slice(0, 3) : someArray).map((user, index) => <li key={index}> {user.name}<li>);
}
</ul>
Upvotes: 1