mvovchak mvovchak - 5 months ago 39
React JSX Question

Truncate a list of names in two lines

I want to display a list of comma-separated names that is coming from an array in my react component. The rendered html looks something like:

<span>Liza</span>, <span>Eric</span>, <span>Michael</span>, <span>Natalie</span>, <span>Stephan</span>
<a href="#" className="show-more hidden">and {remaining} more...</a>

However, this list needs to be displayed in up to 2 lines of content. If the list exceeds the 2 lines, I need to display the quantity of the remaining names that are hidden:

Liza, Eric,

Michael -and 2 more...-

The list also has to be responsive (only display 'X more' if I am truncating) and I need to truncate the list at the end of the last displayed name so the "and X more" text fits within 2 lines.

Can anyone recommend an approach I should take to solve this problem? I believe that pure CSS solution might not work because of the truncation.


PD A screenshot of what I want to achieve:


I guess there are (close to) pure CSS solutions for that. But with react you would something like this:

  1. Render your list of names without any truncation, set the visibility/opacity to hide the elements
  2. Attach a ref callback to every item: <span ref={item => this.items.push(item)}
  3. In componentDidMount() iterate over this.items and sum up the width of the items (item1.width + item2.width ...)
  4. When the sum of widths is greater than the width of the container of the list, you know that you have to truncate the remaining items.
  5. Now you can use internal state or whatever to re-render the list with truncation (this.setState({truncate: true, remainingItemCount: x})
  6. The render function can use this state to figure out how to render the list correctly with truncation (also you can now set the visibility back to normal)