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

Connecting the mat-progress bar to a specific project ID in a mat-table

In my Job Execution screen, there is a list of Jobs along with their status displayed. I am looking to implement an Indeterminate mat-progress bar that will be visible when a Job is executing, and it should disappear once the job status changes to stop or ...

What is the best way to link function calls together dynamically using RXJS?

I am seeking a way to store the result of an initial request and then retrieve that stored value for subsequent requests. Currently, I am utilizing promises and chaining them to achieve this functionality. While my current solution works fine, I am interes ...

Webpack is having trouble resolving the specified file or directory

MyAPP: |--src   |--index.js   |--content.js |--webpack.config.js index.js : const React = require('react'); const ReactDom = require('react-dom'); const View = require('./content'); ReactDom.render(<View/ ...

executing several asynchronous requests upon loading the webpage in a single-page application

As a newcomer to front end development, I have a question about page rendering performance. In my single page application, I have utilized multiple Ajax calls to retrieve data for manipulation in order to enhance performance. However, I am concerned that ...

Encountering an error with the Next Auth adapter in TypeScript when attempting to modify the default User interface

This is my first time using TypeScript and I am attempting to customize the default User interface for next-auth. I have experimented with the following code: next-auth.d.ts import { User } from "next-auth" import { JWT } from "next-auth/j ...

Personalize the position of the v-select drop-down menu

I am currently working with the vuetify v-select component. The problem I am encountering is that instead of the dropdown opening downwards, I need it to open upwards since the dropdown is positioned at the bottom of the page which causes some of the dro ...

Retrieve the current state within a redux action

Many experts recommend consolidating the logic in action creators to streamline the reducer's logic. Picture a basic (normalized) state: const initialState = { parent: { allIds: [0], byId: { 0: { parentProperty: `I'm the ...

The right column in a relatively positioned layout descends as an element in the left column is revealed

Currently in the process of constructing a registration form for our website, everything is going smoothly with one minor hiccup. The form consists of two columns where users enter their information. Initially, when designing elements for the first (left) ...

What are some alternatives to using fetch for making API calls in Next.js?

In my NextJS project, I have an express backend where data fetching is required in getServerSideProps. The issue arises when using await fetch('/api/anyApi'), as it does not work with relative paths, and calling to the absolute path await fetch( ...

Access-Control-Allow-Origin does not permit the origin null

I've been searching for an answer to this question, but I haven't found a suitable one yet. let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState === 4 && xhr.status === 200){ let response = r ...

Passport.js does not provide authentication for server-side asynchronous requests

Recently, I configured Passport.js with the local-strategy on my express server. Interestingly, when I am logged in and send an asynchronous request within NextJS's getInitialProps, it allows the GET request through client-side rendering but not serv ...

What is the best way to divide widgets in a Wordpress Sidebar?

I am looking to customize the spacing between widgets in my Wordpress sidebar, similar to what is shown on this example site. Currently, my sidebar does not have the desired spacing. I have tried various CSS codes found online, but none of them seem to be ...

Ways to expand the width of a div on hover - Angular navbar dropdown utilizing Bootstrap 4

I am attempting to make the div full width while also implementing a slideDown/Up effect. I am struggling to identify the specific CSS needed to adjust the width accordingly. Currently, this is what I have: I can see that the class open is dynamically ad ...

React-Native-SVG encountered an error: Invariant Violation - the component "RNSVGGroup" could not be found in the UIManager

Trying to create an SVG in React-Native using react-native-svg. I have set up a React-Native-CLI. After doing some research, I attempted to solve the issue on my own and found something useful. I tried running cd ios && pod install. I wasn't ...

Issue with automatic form submission

What is the best way to automatically submit my form once the timer runs out and also when the refresh button is clicked? I have encountered an issue where every time I try to refresh the page, it prompts for user confirmation. If I click cancel, it stay ...

Tips on eliminating the gap between two flex items while adjusting their size

Can anyone assist me with my code? Here is the current version: https://i.stack.imgur.com/00RGC.png I want it to resemble this: https://i.stack.imgur.com/JSclD.png You can find all my attempted media queries in the CSS comments at the end. Please let m ...

Identify all div elements with a specific class within the parent div

How can I use query selector to exclusively target the p and p2 divs inside of a r class, without selecting them if they are outside of that class? <div> <div class="r"><div class="p"></div><div class="p2"></div></di ...

Setting up a new folder in the internal storage within a React Native Expo environment

In my React Native Expo project, I am utilizing two functions to store data in a JSON file and then save the file to internal storage. However, the code currently asks for permission to store inside a chosen folder, but does not create the "ProjectName" fo ...

Is there a more efficient method for replacing all attributes on cloned elements?

While this code does the job, I can't help but feel like it's a bit outdated. I'm not very experienced with JS/JQuery and only use them when necessary. My approach involves cloning an element and then replacing all of its attributes with on ...

Display a letter avatar using Material-UI in the absence of an image

How can I display a letter avatar using the Material-UI Avatar React component when there is no image from a specified URL? <Avatar src={ProfileImageUrl} className={classes.avatar}> {userDetails.firstname.charAt(0) + " " + userDetails.lastname. ...