Created
May 9, 2022 01:01
-
-
Save redoPop/184082fcfa28bb14380097457a666f2f to your computer and use it in GitHub Desktop.
React hook to test for content clamping.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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