Condense a lineup of names into only two rows

I have a challenge where I need to showcase a list of names separated by commas, pulled from an array in my React component. The HTML output should appear as follows:

<div>
<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>
</div>

However, it is crucial that this list is displayed within 2 lines of content. If the list exceeds this limit, the number of remaining names that are hidden must be shown:

Liza, Eric,

Michael -and 2 more...-

In addition, the display needs to be responsive (only showing 'X more' when truncating) with the list being cut off at the final visible name so that the "and X more" text fits within 2 lines.

Can anyone suggest an effective approach for solving this problem? I suspect a pure CSS solution may not suffice due to the truncation needed.

Thank you!

PS: An image example of the desired outcome would be helpful.

Answer №1

There may be some CSS solutions for truncating text, but with React, you can achieve this:

  1. Display your list of names without truncation and hide the elements using visibility/opacity
  2. Add a ref callback to each item:
    <span ref={item => this.items.push(item)}
  3. In the componentDidMount() lifecycle method, loop through this.items to calculate the total width of all items (item1.width + item2.width ...)
  4. Once the total width exceeds the container's width, it's time to truncate the remaining items.
  5. Update the internal state or use other means to re-render the list with truncation (
    this.setState({truncate: true, remainingItemCount: x})
    )
  6. The render function can now utilize this state to correctly display the truncated list (you can also revert the visibility back to normal)

Learn more about the ref callback attribute in React documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

implementing GraphQL lists in mutations using Apollo in a React JS application

My current situation involves a mutation that looks like this: orderAdd(products: [ProductInput],restaurant: RestaurantInput) implemented in graphql, and now I want to pass parameters to it using Apollo in react js as shown below: mutation orderAdd ($ ...

Looking for an alternative method since jQuery has deprecated the use of '.toggle()' function

After jQuery deprecated the .toggle() method, I have been searching for a new and simple solution to implement a "Read more" button that slides down a paragraph while changing text to "Read less". Below is the code I have put together: var moreText = "Re ...

Guide on choosing a specific div element from a different page using AJAX

I have a Social Media platform with posts, and I am trying to display the newest ones using JavaScript (JS) and AJAX. I attempted to reload my page using AJAX and insert it into a div element, but now the entire website is loading within that div element, ...

What are the distinguishing factors between using redux saga and redux thunk?

How do you know when to use redux-saga versus redux-thunk? Which one would be more suitable for an ecommerce platform? Is there a noticeable difference in performance between the two? Are thunks faster than sagas? ...

SWR Fails to Recognize Environment Variables

I'm struggling to utilize ENV variables when using the SWR hook for data fetching. My current approach is as follows: const videoURLWithEnv = `https://youtube.googleapis.com/youtube/v3/search?part=snippet&channelId=UCwkj9jcrMZCcbcIa6nF5LNQ&ma ...

Creating a responsive layout with two nested div elements inside a parent div, all styled

I'm currently facing an issue with using padding in my CSS to make the two divs inside a parent div responsive at 50% each. However, when combined, they exceed 100%. I suspect this is due to the padding, but I'm unsure how to resolve it. .column ...

How do I send a 404 error in Node JS Express when a third party API receives a bad request?

I've set up a Node JS server with a route handler that sends a request to a third-party API to retrieve a username: app.get('/players/:player', apiLimiter, function(request, response) { const player = request.params.player; const api_url = ...

Using codeigniter and JQuery, I have developed a unique Javascript function to selectively extract a specific portion of text

I'm currently working with the following syntax: $("#orderbynumber").autocomplete( { source: "get_orders_by_order_number", messages: { noResults: '', results: function() {} }, select: function( event, ui ) { var select ...

What's the best way to handle variables and numerical calculations within PHP loops when dealing with forms?

I'm currently developing a basic PHP page where users can choose how many numbers they want to add together. After selecting the quantity, they input the numbers on a new page, click a button, and then see the sum displayed. The challenge I'm fa ...

Is it possible for GraphQL to communicate with an external API?

I am a beginner in the world of GraphQL and have been wondering if I can utilize it to fetch data from an external, third-party API. Currently, I have an express backend and a react frontend set up and I am making a GET request to a third party API to retr ...

Choose a Different Value for Another HTML Element's Class

Is there a way to preselect an option on another page before it loads? Consider two pages, A and B. If a user clicks a button on page A, I want the default option on page B to be changed to "something" before redirecting them. How can this be achieved s ...

Adding a value to an element in JavaScript to interact with it using Selenium

After implementing the provided code snippet, I noticed that it replaces the value in the element with a new one. However, I am looking to append or insert a new line rather than just replacing the existing value. Is there an alternative command like app ...

Is it possible to modify the number format of an input field while in Antd's table-row-edit mode?

I am currently utilizing the Table Component of Ant Design v2.x and unfortunately, I cannot conduct an upgrade. My concern lies with the inconsistent formatting of numbers in row-edit mode. In Display mode, I have German formatting (which is desired), but ...

Can an object serve as a property name for another object?

Can this be achieved using JavaScript? I'm attempting to assign the property name of an object as a "HTMLInputElement": var el = $('#something').get(0), obj = {}; obj[el] = 'some random data'; Unfortunately, it ...

Enhancing the Strength of Password Generator

Example of a Simple Password Generator: function createPassword() { var characters = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOP" + "1234567890" + "@\#\-!$%^&*()_+|~=`{}\[\]:\";& ...

Tips for displaying the Max Window Icon (TitleBar) in ReactJS

Can someone help me with displaying the Sample Title Bar only in the Icon Window Max section using this code? import React from 'react' import { TitleBar } from 'react-desktop/windows'; export default function App() { return ( &l ...

Illuminate specific areas of a mapped image upon hovering over text on a webpage

Scenario: There is an image on the page with various mapped areas. A list of text elements is also present on the page. Desired functionality: Hovering over different text items in the list should result in highlighting corresponding areas on the mappe ...

Looking for assistance with aligning a form in the center?

After spending the last hour trying to center a form for a name without success, I have decided to seek help here. Although I have searched extensively, I am still struggling at this point. Here is my HTML: <div id="main" class="main"> <tabl ...

Uncertain about the process of accessing req.body data

I'm having trouble retrieving the body data on my server, even with simple .get requests. Despite simplifying it to just a basic call, I still can't seem to access the body data. This issue is hindering more complex calls that require accessing t ...

The type does not contain a property named `sort`

"The error message 'Property sort does not exist on type (and then shoes4men | shoes4women | shoes4kids)' pops up when attempting to use category.sort(). I find it puzzling since I can successfully work with count and add a thousand separato ...