emert117
emert117

Reputation: 1488

React multiple a tag inside li tag

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?

Upvotes: 1

Views: 1265

Answers (2)

emert117
emert117

Reputation: 1488

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

Upvotes: 0

Alex Wayne
Alex Wayne

Reputation: 187024

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>

Upvotes: 1

Related Questions