0

I'm really struggling to understand what's wrong with the syntax in the following react function

    const listItem = (parentId) => {
            var childCategories = categories.filter(category => category.ParentId === parentId)
            return (
                childCategories.map(category => (
                    <ListItem key={category.Id} button>
                        <ListItemText primary={category.Name} />
                    </ListItem>
                    listItem(category.Id) //// it doesn't like this line
                ))
            )
        }

if I take out the line with the comment "//// it doesn't like this line" the function works except of course there is no recursion. I've tried all different combinations of {} and() e.g. {listItem(category.Id)} but it still doesn't work. Any idea what's wrong with the syntax.

Stephen Clay
  • 107
  • 7
  • 1
    try this also https://stackoverflow.com/questions/22876978/loop-inside-react-jsx – shaked keynan Oct 27 '20 at 15:14
  • Can you include the whole component in your question? – Alex Yepes Oct 27 '20 at 15:17
  • Does this answer your question? [How to return multiple lines JSX in another return statement in React?](https://stackoverflow.com/questions/23840997/how-to-return-multiple-lines-jsx-in-another-return-statement-in-react) – Emile Bergeron Oct 27 '20 at 15:37

1 Answers1

5

This is a syntax error and not related to React, in return statement you can only return a single expression.

return [[expression]]; 

What you have written is similar to:

array.map(item => { 
 return (item item) // syntax error
})

So in this case for React, to return a single value you can use React.Fragment:

<>
  <ListItem key={category.Id} button>
    <ListItemText primary={category.Name} />
  </ListItem>
  {listItem(category.Id)}
</>
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118