Reputation: 1488
I can render nested data with React. For example:
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:
This is my data:
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>
What I try to achieve: (Please look at 6th li tag)
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
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:
Thanks to @AlexWayne
Upvotes: 0
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