Skip to content

Instantly share code, notes, and snippets.

@redoPop
Created May 9, 2022 01:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redoPop/184082fcfa28bb14380097457a666f2f to your computer and use it in GitHub Desktop.
Save redoPop/184082fcfa28bb14380097457a666f2f to your computer and use it in GitHub Desktop.
React hook to test for content clamping.
import * as React from 'react';
type ElRef = React.RefCallback<HTMLElement>;
/**
* Uses content height to determine if an element has been clamped.
*
* Useful for creating "Read more" buttons with CSS line-clamp.
*
* #### Example:
* ```jsx
* const [isClamped, elRef] = useClampCheck();
* const [expand, setExpand] = React.useState(false);
*
* <div ref={elRef} className={expand ? '' : 'line-clamp-2'}>
* Lots and lots of words…
* </div>
* {isClamped && (
* <button onClick={() => setExpand(true)}>
* Read more
* </button>
* )}
* ```
*/
export default function useClampCheck(): [boolean, ElRef] {
const [clamped, setClamped] = React.useState(false);
const ref: ElRef = el => setClamped(
Boolean(el && el.scrollHeight > el.clientHeight)
);
return [clamped, ref];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment