I try to bind the list <li>
using .map()
in React but it is not working out. To me it seems to be the issue of using either (
or {
properly. If I can get some guidelines here that would be so helpful.
While trying to bind the list, the code works as expected without any issue and without if
statement.
As soon as I start writing if
condition, it doesn’t like it.
Here is my code that works without if
statement. It is a simple list <li>
.
let currentTopic = '';
return (
<div>
{
<ul>
{
topics.map((t) => (
<>
<span>{t.topicName}</span>
<li key={t.productId} value={t.subTopic}>
{t.subTopic}
</li>
</>
))
}
</ul>
}
</div>
);
Below code I am trying to make it work with if
statement. The topicName
repeats depending on data in topics
so by using if
I am trying to put a check if it repeats than it should not print again. Something like below.
<ul>
{
topics.map((topic) => (
topic.topicName != currentTopic
? (<><span>{topic.topicName}</span><li key={topic.productId} value={topic.subTopic}>
{topic.subTopic}
</li></>) : null
,currentTopic = topic.topicName
))
}
</ul>
I tried following below references from stackoverflow, but somehow I feel I am not able to set the syntax properly.
3
Answers
Only using map without filter
Comma operator (,)
The comma (,) operator evaluates each of its operands (from left to right) and returns the value of the last operand. This is commonly used to provide multiple updaters to a for loop’s afterthought.
(topic.topicName != currentTopic ? () : null,currentTopic = topic.topicName)
It will return currentTopic = topic.topicName
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_operator
Because there is a comma operator after the ternary condition in your
map
function.This will be interpreted as
which will aways return
statement
after the comma operator, the return value ofcurrentTopic = topic.topicName
.If you want to have some extra logic inside one of the ternary operation, consider changing the structure a little bit:
But as you can see, it’s getting really messy here. My suggestion is to use a proper function body with if condition: