samuelweckstrom / react-ascii-text

ASCII text art renderer
7 stars 1 forks source link

Type mismatch: `MutableRefObject` & `LegacyRef` #3

Closed currenthandle closed 7 months ago

currenthandle commented 7 months ago

When I do this, basic example:

export default function Banner() {

  const asciiTextRef = useAsciiText({
    animationCharacters: '▒ ░ █',
    font: ansiShadow,
    text: ['MY STRING', 'MY STRING'],
    fadeIn: true,
    animationDirection: 'down',
  })

  return (
    <div className='h-48'>
      <h1 className='text-z-red text-2xl'>
        <pre ref={asciiTextRef}></pre>
      </h1>
    </div>
  )
}

I get this type error:

Diagnostics:
1. Type 'MutableRefObject<HTMLPreElement | undefined>' is not assignable to type 'LegacyRef<HTMLPreElement> | undefined'.
     Type 'MutableRefObject<HTMLPreElement | undefined>' is not assignable to type 'RefObject<HTMLPreElement>'.
       Types of property 'current' are incompatible.
         Type 'HTMLPreElement | undefined' is not assignable to type 'HTMLPreElement | null'.
           Type 'undefined' is not assignable to type 'HTMLPreElement | null'. [2322]

Work around:

export default function Banner() {
  const asciiTextRef = useAsciiText({
    animationCharacters: '▒ ░ █',
    font: ansiShadow,
    text: ['MY STRING', 'MY STRING'],
    fadeIn: true,
    animationDirection: 'down',
  })

  // Using a ref callback to bridge the type mismatch.
  const refCallback = (element: HTMLPreElement | null) => {
    if (asciiTextRef) {
      // Directly manipulate the `.current` property only if it's not `undefined`.
      asciiTextRef.current = element ?? undefined // Convert `null` to `undefined`.
    }
  }

  return (
    <div className='h-48'>
      <h1 className='text-z-red text-2xl'>
        <pre ref={refCallback}></pre>
      </h1>
    </div>
  )
}