use-expand-collapse.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { useRef, useState, useLayoutEffect } from 'react'
  2. import classNames from 'classnames'
  3. function useExpandCollapse({
  4. initiallyExpanded = false,
  5. collapsedSize = '0',
  6. dimension = 'height',
  7. classes = {}
  8. } = {}) {
  9. const ref = useRef()
  10. const [isExpanded, setIsExpanded] = useState(initiallyExpanded)
  11. const [size, setSize] = useState()
  12. useLayoutEffect(
  13. () => {
  14. const expandCollapseEl = ref.current
  15. if (isExpanded) {
  16. const expandedSize =
  17. dimension === 'height'
  18. ? expandCollapseEl.scrollHeight
  19. : expandCollapseEl.scrollWidth
  20. setSize(expandedSize)
  21. } else {
  22. setSize(collapsedSize)
  23. }
  24. },
  25. [isExpanded]
  26. )
  27. const expandableClasses = classNames(
  28. 'expand-collapse-container',
  29. classes.container,
  30. !isExpanded ? classes.containerCollapsed : null
  31. )
  32. function handleToggle() {
  33. setIsExpanded(!isExpanded)
  34. }
  35. return {
  36. isExpanded,
  37. expandableProps: {
  38. ref,
  39. style: {
  40. [dimension === 'height' ? 'height' : 'width']: `${size}px`
  41. },
  42. className: expandableClasses
  43. },
  44. toggleProps: {
  45. onClick: handleToggle
  46. }
  47. }
  48. }
  49. export default useExpandCollapse