Luisa Silva
Luisa Silva

Reputation: 159

React/Typescript: Selected items counter logic

I've been trying to create a selection list with a counter. The goal is to be able to select as many items as I wish and have a small tag with the item name for the two first selected items. As for the other items, I would like to have a counter that displays '+ {the number of the remaining selected items}'. However, I'm a little stuck with the logic for the counter. What would be the best approach and syntax to make it work? Thanks a lot!

import { Tag } from './Tag';

type TagSize =  'sm' | 'md' | 'lg' ;

export type TagListProps = {
  items: Array<{
    id: string;
    label: string;
  }>;
  limit?: number;
  size?: TagSize;
  onRemove?(id: string): void;
};

export function TagList({
  items,
  limit,
  size = 'sm',
  onRemove
}: TagListProps): JSX.Element {

  const tags = limit ? items.slice(0, limit) : items;
  const counter = items.length - tags.length;

  return (
    <div className='tag-list'>
      {
        tags.map((tag) => (
          <Tag size={ size } className='single-tag' key='' removable onRemove={ () => onRemove(tag.id) }>
            { tag.label }
          </Tag>
        ))
      }

//that's the logic where I'm getting stuck 

      {  limit  && (
      <div className='items-counter'>
        { counter }
      </div>
        ) }

    </div>
  );
}

Upvotes: 1

Views: 222

Answers (2)

Luisa Silva
Luisa Silva

Reputation: 159

Resolution:

Turns out that the solution was quite simple and as @Cody mentions in one of the comments, the limit has to be set according to the array length (items.length > limit). Here's how it looks like resolved:


type TagSize =  'sm' | 'md' | 'lg' ;

export type TagListProps = {
  items: Array<{
    id: string;
    label: string;
  }>;
  limit?: number;
  size?: TagSize;
  onRemove?(id: string): void;
};

export function TagList({
  items,
  limit,
  size = 'sm',
  onRemove
}: TagListProps): JSX.Element {

  const tags = limit ? items.slice(0, limit) : items;
  const counter = items.length - tags.length;

  return (
    <div className='tag-list'>
      {
        tags.map((tag) => (
          <Tag size={ size } className='single-tag' key='' removable onRemove={ () => onRemove(tag.id) }>
            { tag.label }
          </Tag>
        ))
      }

//that's the logic where I'm getting stuck 

      { items.length > limit && (
      <div className='items-counter'>
        { counter }
      </div>
        ) }

    </div>
  );
}``

Upvotes: 1

Cody E
Cody E

Reputation: 189

Is it possible your limit is greater than the length of the items array? If that is the case, this will always display 0.

Upvotes: 1

Related Questions