Reputation:
Is there any way I can shorten this code? The only difference is that I want at index 0 to display 'All' instead of array value.
Or maybe multiple condition? like at index = 0, do this, index which is %2, do this, and last index, do this?
I also found the same solution. I got another problem now,
I want to choose between two function in a onClick.
<a onClick={()=>{AddNewBookmark(userId, newsId); this.changeBookmarkState(isBookmarked, bookmarkIndex);}}>
I want is index == 0 to use AddNewBookmark(userId, newsId) or if index == 1 then use RemoveBookmark(userId, newsId).
<a onClick={()=>{ index == 0 ? AddNewBookmark(userId, newsId) :
RemoveBookmark(userId, newsId); this.changeBookmarkState(isBookmarked,
bookmarkIndex);}}>
I want the changebookmarkstate to be included no matter what index value.
My attempt didnt work somehow. Any suggestion?
Upvotes: 0
Views: 102
Reputation: 174
Since all you're doing is changing what gets rendered in the span, you can do your logic in JSX inside the span
This should work:
isFiltered[index] && (
<div key={index}>
<span>{index == 0 ? "All" : category['Name']}</span>
</div>
);
You could also extract this logic into a function, and then call the function in the span. This would be cleaner if you end up wanting to display a bunch of different results in that span. Something like this:
helperFucntion(index: number) => (
index == 0 ? "All" : category['Name']
)
isFiltered[index] && (
<div key={index}>
<span>{helperFunction(index)}</span>
</div>
);
Upvotes: 2
Reputation: 509
The shortest form of your code could be like this:
isFiltered[index] && return (
<div key={index}>
<span">{ index ? "ALL" : category['Name'] }</span>
</div>
);
Upvotes: 1
Reputation: 792
Your code seems incomplete so I can't be sure but you can use following, based upon your need.
You can insert a new index in start of array.
isFiltered.unshift['All'];
if (isFiltered[index]){
return (
<div key={index}>
<span>{ category['Name']}</span>
</div>
);
}
Upvotes: 0