Veronica
Veronica

Reputation: 71

add bullets (•) between html links except last item dynamically generated links in React

I am rendering data dynamically in React after making an api call, then mapping through the results to show links to websites in a table. All is working as intended except that I need to add bullets between each link to segment the content for the user (any number of links per row - it can be one up to ten). I need to make sure there is NOT a trailing bullet if there is only one link rendered per row as well as not add a bullet behind the last link in a row if there is more than one. Below is working code, you can see the html • after the {data.title}

<table className="graph-table">
    <thead>
        <tr id="table-header" className="table-row">
        </tr>
    </thead>
    <tbody>
        { displayData.map( ( item, i ) => {
            return (
                <tr className="table-row">
                    <td> { item.categoriesArray.map(( {data}) => { return  <a href={data.uri}> {data.title} &bull;</a> })}
                    </td>
                </tr>
            )
          })
        }
    </tbody>
</table>

The output is:

row 1 link 1 • link 2 •
row 2 link 1 •
row 3 link 1 • link 2 • link 3

It works if there is the right number of links (as seen in row 3), I just don't have control of the data I get back, I need to smartly add bullets.

Thanks in advance.

Upvotes: 1

Views: 2680

Answers (1)

epascarello
epascarello

Reputation: 207527

I mentioned you can just add the bullets with CSS

.table-row a {
  text-decoration: none;
}
.table-row a::after {
  content: " \2022";
}
a:last-child::after {
  content: ""
}
<div class="table-row">
  <a href="#">a</a>
  <a href="#">b</a>
  <a href="#">c</a>
</div>

<div class="table-row">
  <a href="#">a</a>
  <a href="#">b</a>
</div>


<div class="table-row">
  <a href="#">a</a>
</div>

If you do not want to do it with CSS, than you would need to add a check the index on your loop. If it is not the last, than add the bullet.

I am not a react dev, but basic idea with ES6 would be

var links = [{uri:"a", title:"aa"},{uri:"b", title:"bb"},{uri:"c", title:"cc"}];
console.log(links.map( (data, i, a) => { let bull = (i+1!==a.length) ? ' &bull;' : ''; return `<a href="${data.uri}"> ${data.title}${bull}</a>`; }));

Upvotes: 1

Related Questions