Include "+5" in cases where additional elements cannot be accommodated

I am working on a project where I have a div called ItemsContainer that dynamically renders an array of items (Item) depending on the screen size.

While mapping through the array, I want to check if there is enough space to display the current item. If not, I would like to stop rendering the items and instead add a special item that shows how many more items are in the array but not displayed. Check out the image for clarification.

This is what my code looks like so far using React with TypeScript. I haven't implemented the additional "+5" box yet because I'm unsure if it's feasible. My initial plan was to display a fixed number of items and then show the "+X" item if there are more hidden items, but I hope to find a more dynamic solution.

const Items: FC<Props> = ({ items }) => {
  return (
    <ItemsContainer>
      {items.map((item, index) => (
        <Item key={index}>{item.name}</Item>
      ))}
    </ItemsContainer>
  );
};

https://i.sstatic.net/ZVp2V.png

Answer №1

Check out this solution that is partially functional: https://codepen.io/Latcarf/pen/WNKZmBN.

The key aspect of the code lies in the following:

const Tags = ({tags}) => {
  const [hiddenCount, setHiddenCount] = React.useState(0)
  const shownTags = hiddenCount == 0 ? tags : tags.slice(0, -hiddenCount);
  const ref = React.useRef();

  React.useLayoutEffect(() => {
    if (!ref.current) {
      return;
    }
    if (ref.current.scrollWidth > ref.current.clientWidth) {
      setHiddenCount(count => count + 1);
    }
  });
  
  return (
    <div class="container" ref={ref}>
      {shownTags.map(tag => <div class="tag">{tag}</div>)}
      {hiddenCount > 0 && <div class="tag">{`+${hiddenCount}`}</div>}
    </div>
  )
};

The concept involves maintaining a state variable called hiddenCount to keep track of the number of hidden tags. It begins at 0 and incrementally adjusts until enough space is available, although handling numerous hidden items may lead to multiple rerenders before reaching the correct count. Nevertheless, it effectively addresses scenarios where displaying +1 would exceed the length of showing the last tag.

To ensure automatic updates on resizing, you could utilize a useResizeObserver hook to reset hiddenCount to 0 post-resize. Despite my difficulties importing additional packages in CodePen, I created a button for triggering a rerender to facilitate testing (resize the div then click the button).

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

Is there a way to retrieve all IDs within an array of objects using a foreach loop and merge the data associated with each ID?

I am currently working on a TypeScript API where I have merged all the data from this API with some additional data obtained from another API function. I have provided a snippet of my code which adds data to the first index of an array. M ...

Status of Google Sheets sidebar being opened or closed

I am currently seeking a method to monitor the status of the sidebar within Google Sheets. My understanding is that I can ascertain which sidebar HTML has been accessed by establishing a global variable before the HTML content is presented. Given that onl ...

Enhancing Autocomplete in React MUI with custom styles for the Popper component

Looking to customize the width of the Popper within the Autocomplete component in my project. The Autocomplete is placed within a parent component, next to a TextField. Check out the Codesandbox snippet here: https://codesandbox.io/s/basictextfields-mate ...

Remove the formatting on the entered text

Hi, I'm looking to change the style of my input text to a strike-through style. Can anyone help me with this? <input type="text" value="<del>Hello World!</del>" /> I would like my input text to look like this: ...

Handling right-click events with jQuery live('click')

There has been an interesting observation regarding the functionality of the live() function in jQuery: <a href="#" id="normal">normal</a> <a href="#" id="live">live</a> $('#normal').click(clickHandler); $('#live&ap ...

How can you specify a tuple type in TypeScript for an array that is empty?

I'm attempting to convert a const object into a class in order to create readonly properties. The goal is to ensure that the values in these properties never change. Specifically, I'm trying to create a module property in my class that is define ...

How to immediately set focus on a form control in Angular Material without needing a click event

Currently working with Angular 9 and Material, we have implemented a Stepper to assist users in navigating through our workflow steps. Our goal is to enable users to go through these steps using only the keyboard, without relying on mouse clicks for contro ...

Ways to identify if the text entered in a text area is right-to-left justified

Within a textarea, users can input text in English (or any other left-to-right language) or in a right-to-left language. If the user types in a right-to-left language, they must press Right-shift + ctrl to align the text to the right. However, on modern O ...

Different width can be set for the Google Maps template specifically for mobile mode by following these steps

Is there a way to adjust the width of a Google Maps template specifically for mobile mode? While it looks perfect on desktop, the map overflows the screen size on mobile. See my code snippet below: @section ('map') <div id="map"></d ...

Utilizing Express-WS app and TypeScript to manage sessions

I am currently working on setting up a node server using Typescript with the help of express and express-ws. My goal is to include Sessions in my application, so I have implemented express-session. Below you can find some pseudo code: import * as session ...

Webpack struggles with handling css using the css-loader when trying to implement (react)-css-modules

Trying to set up webpack with react and (react)-css-modules, but encountering an issue where webpack is unable to parse the css. This is the standard configuration being used. const webpack = require("webpack"), merge = require("webpack-merge"), path ...

Extracting data from website tables

I've been attempting to retrieve salary information for CSU employees from a specific webpage (). Despite my efforts with the urllib2 and requests libraries, I have not been successful in extracting the table data from the webpage. My suspicion is tha ...

Regular Expressions in action - Substituting text within an eZ Publish XML field

Before utilizing the eZ Publish 5 API to create an Xml content, I need to make some modifications. I am currently working on implementing a Regex to edit the content. Below is the Xml code I have (with html entities) : View Xml code here http://img15.ho ...

Restricting the Zoom Functionality in a Web-Based Project on a Touch-Enabled Display

I am currently working on a project that is web-based and runs on localhost. I need to prevent users from zooming in on the user interface. Is there a way to accomplish this using JavaScript? And can I achieve this restriction specifically on Google Chrome ...

Moving the element from the right side

Is there a way to change the direction of this element's transition from left to right, so that it transitions from right to left smoothly without any gaps between the element and the edge of the page? @keyframes slideInFromRight { 0% { trans ...

Disable the shadow on the focused state of Safari and Chrome dropdown selects

I'm attempting to eliminate the shadow that appears on a select element when it is in focus: https://i.sstatic.net/5kDKE.png I have tried the following CSS styles: select { border: none; box-shadow: none; -webkit-box-shadow: none; o ...

Unable to load Angular 2 Tour of Heroes application due to Typescript issue

My Angular 2 Tour of Heroes app seems to be stuck on the "Loading..." screen and I can't seem to figure out why. The angular-cli isn't showing any errors either. I'm currently at part five of the tutorial and it's becoming quite frustra ...

Struggling to locate the reCAPTCHA button using Selenium

My current challenge involves dealing with a recapture using selenium. I need to locate it on the page and click on it, but I'm unable to find it even though it's visible on the page. Here's my code: def capthcha(url = "https://google. ...

How to ensure text wraps when resizing window in CSS? The importance of responsive design

UPDATE: I finally fixed my scaling issues by setting the max-width to 760px. Thank you for the tip! However, a new problem has emerged - now my navigation scales in the small window and I want it to remain a fixed size. Hello everyone! I am currently lear ...

Guide on incorporating a Heroku deployed API into Vercel for optimizing images

My website's front-end is live on Vercel, while the back-end is hosted on Heroku. I'm struggling to figure out how to properly integrate the API endpoint into my next.config.js file so that my images can be displayed correctly. Here are some th ...