1

I can render nested data with React. For example:

  1. text1, text2
  2. text1, text2, text3

I combine strings to get "text1, text2"

allSynonymText += synonym.SynonymText + ', ';

I want to make links instead of combined text inside of a li tag. For example:

  1. link1, link2
  2. link1, link2, link3

This is my data:

enter image description here

My code:

<div>
<p><span>Synonyms</span></p>
<ul>
    {word.Definitions.map((definition, index) => {
        if (definition.Synonyms !== null && definition.Synonyms.length > 0) {
            let allSynonymText = '';
            definition.Synonyms.map((synonym) => {
                allSynonymText += synonym.SynonymText + ', '; // I combine texts here
            })
            return <li>{index + 1}. {allSynonymText}</li>
        }                            
    }
    )}
</ul>
</div>

This is what I get: enter image description here

What I try to achieve: (Please look at 6th li tag)

enter image description here

I am new to React. I searched and tried many things but I couldn't achieve it.

How can I insert multiple links inside of a li tag?

emert117
  • 1,268
  • 2
  • 20
  • 38
  • Does this answer your question? [Loop inside React JSX](https://stackoverflow.com/questions/22876978/loop-inside-react-jsx) – Dan O Jul 07 '20 at 21:03
  • @DanO unfortunately no. I can create multiple li tags inside of ul tag. All of the examples are for this logic. I need to place links inside of a li tag. I need a second iteration in rendering. – emert117 Jul 07 '20 at 21:12

2 Answers2

1

You can use map between {} in JSX in order to return an array.

And you can use a fragment <>{}</> to return the link and your comma as a single element.

Putting those together you get something like:

return <li>
  {index + 1}.
  {definition.Synonyms.map(synonym => (
    <>
      <a href={`/synonyms/${synonym.synonymID}`}>
        {synonym.synonymText}
      </a>,
    </>
  )}
</li>
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • Thanks. It helped me a lot. I made a few changes to your answer and it worked. I used `` instead of `<>` and I added `return` inside of the `Synonyms.map` – emert117 Jul 08 '20 at 05:14
0

I changed my code to this:

<div>
<p><span>Synonyms</span></p>
<ul>
    {word.Definitions.map((definition, index) => {
        if (definition.Synonyms !== null && definition.Synonyms.length > 0) {
            return <li>
                {index + 1}.
                {definition.Synonyms.map(synonym => {
                    // return new span for each synonym
                    // and place the link inside of the span
                    return <span><a href={`/?wq=${synonym.SynonymText}`}>{synonym.SynonymText}</a> , </span>
                }
                )}
            </li>
        }                            
    }
    )}
</ul>

This is the result:

enter image description here

Thanks to @AlexWayne

emert117
  • 1,268
  • 2
  • 20
  • 38