Removing The Last Comma From An Iteration In React Javascript Enter a brief summary for this post

Removing The Last Comma from an Iteration in React Javascript

Just a short blog post about removing the last comma from a React Javascript iteration using map. There is in fact one way of doing so with Javascript (see below) but also there is a way using bare bones CSS. To give you some context, look at the following React components. We pass in a data set to the Url component to begin with.

const Url = (props) => {
	return (
		<>
			{
				props.items.map(item => { 
					return (
						<UrlItem key={item.id} item={item} users={item.users} />
					)}
				)
			}
		</>
	);
};

export default Url;

This takes the data set and iterates over it, creating a new UrlItem component for each data. But it's not this iteration we concern ourselves with but a secondary iteration. Because there can be one or more users who have added the same web page url to the database. A one-to-many relation in other words.

Moving on, we have the UrlItem component.

import UrlUserItem from "./User/UrlUserItem";

const UrlItem = (props) => {
	return (
		<>
			<div className="card my-1 mb-2">
				<div className="card-body">
					<span className="py-2">Added by&nbsp;
    				{
    					props.users.map((user, i) => { 
							return (
								<UrlUserItem key={user.id} index={i} user={user} size={props.users.length} />
							)}
						)
					}, {props.item.human_friendly}</span>
					<h3 className="card-title">
    					<a className="truncate" target="_blank" rel="noopener, noreferrer" href={`${props.item.url}`}>{props.item.title}</a>
    				</h3>
    				
    			</div>
			</div>
		</>
	);
};

export default UrlItem;

This component houses the secondary iteration and the UrlUserItem component which represents a React Link.

const UrlUserItem = (props) => {

	return (
		<>
			{
				props.index > 2 ? ( 
					<>
						and others
					</>
				) : (
					<Link to={`/user/${props.user.slug}`}>
						{props.user.username}
					</Link>
				)
			}{props.index +1 !== props.size && ","}&nbsp;
		</>
	);
};

export default UrlUserItem;

Looking closer if there are more than two users then I cut it short with and others as seen with social media. I prefer to not to remove a comma (so the title is a little misleading) but to actually add one if and when appropriate. That's taken care of with the following expression:

  • {props.index +1 !== props.size && ","}&nbsp;

I'm not sure if length is a reserved word or not in Javascript but rather than take the chance it is I use props.size instead of props.length. As for the CSS solution, put the following into your stylesheet.

.username:not(:last-child)::after { 
		content: ',';
	}