2.0.5 • Published 1 year ago

@yukimoto/use-clamp-text v2.0.5

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

use-clamp-text hook: useClampText

Custom react hook that clamp multiline text to a specified line number. Can optionally specify trailing spaces. Fix some bugs and use cleaner implementation. Modified from:

Install

npm i @yukimoto/use-clamp-text

Usage

const component = () => {
  const {
    longEnoughToClamp,
    textContainerRef,
    addOnsContainerRef,
    wrapperContainerRef,
    clamped,
    clampedText,
    toggleClamp,
  } = useClampText<{
    WrapperContainer: HTMLDivElement;
    TextContainer: HTMLSpanElement;
    AddonsContainer: HTMLButtonElement;
  }>({
    originalText: 'some potentially really long text...',
    lines: 2, // At most how many lines
    endSpaceNumber: 4, // how many trailing space,
    unitSpaceChar: '*', // single trailing space should be the width of this char
    debounceTime: 100, // in miliseconds
  });
  return (
    <div ref={wrapperContainerRef}>
      <span ref={textContainerRef}>{clampedText}</span>
      {longEnoughToClamp ? (
        <button ref={addOnsContainerRef} onClick={toggleClamp}>
          {clamped ? '...show more' : '...show less'}
        </button>
      ) : null}
    </div>
  );
};

API reference

Arguments

propertytyperequireddefaultdescription
originalTextstringfalse''Text you wish to clamp.
linesnumberfalse2Number of visible lines when collapsed.
debounceTimenumberfalse300How many time in miliseconds before the clamp action will be triggered when window resizes.
minSpaceCharNumnumberfalse0The minium trailing space number, will make the process of adding space to the end of the addons component more efficient.
unitSpaceCharstringfalse'.'The width of single trailing space, pass a char for the measurement of width.
endSpaceNumbernumberfalse0How many trailing spaces. Each of them will be the width of unitSpaceChar.

Returns

propertytypedescription
longEnoughtToClampbooleanWhether the originalText is longer enough to exceeds the given line number by it self.
clampedTextstringThe string to be rendered.
clampedbooleanA state indicating whether the text should be clamped if long enough.
toggleClamp() => voidA callback which togger the clamped state.
wrapperContainerRef, textContainerRef, addOnsContainerRefReact.RefObject<E extends HTMLElement>Ref for corresponding containers.
2.0.5

1 year ago

2.0.4

1 year ago

2.0.3

1 year ago

2.0.2

1 year ago

2.0.1

1 year ago

2.0.0

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago