Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix useDynamicTextareaHeight initial render with slots #3196

Merged
merged 11 commits into from
Jun 20, 2023
5 changes: 5 additions & 0 deletions .changeset/pink-papayas-relate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@primer/react": patch
---

Fix `useDynamicTextareaHeight` initial render with slots
13 changes: 11 additions & 2 deletions src/drafts/hooks/useDynamicTextareaHeight.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {RefObject, useLayoutEffect, useState} from 'react'
import {RefObject, useCallback, useEffect, useLayoutEffect, useState} from 'react'

import {SxProp} from '../../sx'
import {getCharacterCoordinates} from '../utils/character-coordinates'
Expand Down Expand Up @@ -34,7 +34,7 @@ export const useDynamicTextareaHeight = ({
const [minHeight, setMinHeight] = useState<string | undefined>(undefined)
const [maxHeight, setMaxHeight] = useState<string | undefined>(undefined)

useLayoutEffect(() => {
const refreshHeight = useCallback(() => {
if (disabled) return

const element = elementRef.current
Expand All @@ -60,8 +60,17 @@ export const useDynamicTextareaHeight = ({
if (minHeightLines !== undefined) setMinHeight(`calc(${minHeightLines} * ${lineHeight})`)
if (maxHeightLines !== undefined) setMaxHeight(`calc(${maxHeightLines} * ${lineHeight})`)
// `value` is an unnecessary dependency but it enables us to recalculate as the user types
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [minHeightLines, maxHeightLines, value, elementRef, disabled])

useLayoutEffect(refreshHeight, [refreshHeight])

// With Slots, initial render of the component is delayed and so the initial layout effect can occur
// before the target element has actually been calculated in the DOM. But if we only use regular effects,
// there will be a visible flash on initial render when not using slots
iansan5653 marked this conversation as resolved.
Show resolved Hide resolved
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(refreshHeight, [])

if (disabled) return {}

return {height, minHeight, maxHeight, boxSizing: 'content-box'}
Expand Down