.color-list__item {
  margin: 0.25rem; /* We need to know the margin size in the JS file */
}

color-list.css hosted with ❤ by GitHub
.color-swatch {
  width: 10rem; /* We need to know this width in the JS file */
}
/** 
 * Determines how many items can fit on one line, 
 * given the line width and item width.
 */
const getMaxItemsPerLine = (lineWidth, itemSize) =>
  Math.floor(lineWidth / itemSize);

/**
 * Determines if the item should be hidden, given
 * the items index and the max number of items allowed
 * on one line.
 */
const isItemHidden = (maxItemsPerLine, itemIndex) =>
  itemIndex > maxItemsPerLine - 1;

export const ColorList = ({ colorSwatches, handleClick }) => {
  const [listWidth, setListWidth] = React.useState(-1);
  
  // Here are the values from our CSS files
  const colorSwatchSize = 160; // px, equivalent to the 10rem width assuming our root font-size is 16px
  const listItemMargin = 4; // px, equivalent to the 0.25rem width assuming our root font-size is 16px
  
  const colorSwatchTotalWidth = colorSwatchSize + 2 * listItemMargin;
  const maxItemsPerLine = getMaxItemsPerLine(listWidth, colorSwatchTotalWidth);

  return (
    <div className="color-list__container">
      <Measure
        bounds
        onResize={contentRect => setListWidth(contentRect.bounds.width)}
      >
        {({ measureRef }) => (
          <ul ref={measureRef} className="color-list">
            {colorSwatches.map((colorInfo, i) => {
              const hidden = isItemHidden(maxItemsPerLine, i); {/* Item will be hidden if doesn't fit on the first line */}
              return (
                <li key={i} className="color-list__item" hidden={hidden}>
                  <ColorSwatch
                    element="button"
                    {...colorInfo}
                    onClick={handleClick(colorInfo)}
                    disabled={hidden}
                  />
                </li>
              );
            })}
          </ul>
        )}
      </Measure>
    </div>
  );
};

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.