Home > database >  React/Typescript - when using ref I get typescript error - Property 'current' does not exi
React/Typescript - when using ref I get typescript error - Property 'current' does not exi

Time:09-15

I have a component that receives a ref prop:

import React, {forwardRef, ReactElement, ReactNode, HTMLProps, useRef} from 'react'
import styles from './index.module.css'
import classNames from 'classnames'
import { IconFa } from '../icon-fa'
import { useStableId } from '../use-stable-id'

export interface Props extends HTMLProps<HTMLInputElement> {
  // An icon component to show on the left.
  icon?: ReactNode
  // A help text tooltip to show on the right.
  help?: string
  // A clear text tooltip to show on the right.
  clear?: string
  // Pass an onHelp click handler to show a help button.
  onHelp?: () => void
  // Pass an onClear click handler to show a clear button.
  onClear?: () => void
  errorMessage?: ReactNode
  label?: string
  hideLabel?: boolean
}

export const FormInput = forwardRef<HTMLInputElement, Props>(function FormInput(props, ref): ReactElement {
  const { id, icon, help, hideLabel, errorMessage, onHelp, onClear, ...rest } = props
  const stableId = useStableId()
  const inputId = id ? id : stableId

  console.log(ref.current)

  const inputClassName = classNames(
    styles.input,
    icon && styles.hasLeftIcon,
    (help || onHelp || onClear) && styles.hasRightIcon
  )

  const labelClassName = classNames(
    styles.label,
    Boolean(props.value) && styles.hasValue,
    props['aria-invalid'] && styles.hasError,
    props.className
  )

  return (
    <div className={labelClassName}>
      {!hideLabel && (
        <label className={styles.labelText} htmlFor={inputId}>
          {props.label}
          {props.required && '*'}
        </label>
      )}
      <div className="relative">
        {icon && <div className={styles.leftIcon}>{icon}</div>}
        <input
          {...rest}
          id={inputId}
          ref={ref}
          aria-invalid={props['aria-invalid']}
          aria-label={props.hideLabel ? props.label : undefined}
          className={inputClassName}
        />
        {onClear && <ClearIcon {...props} />}
        {!onClear && (help || onHelp) && <HelpIcon {...props} />}
      </div>
      {props['aria-invalid'] && <span className={styles.error}>{errorMessage}</span>}
    </div>
  )
})

function HelpIcon(props: Props) {
  if (props.onHelp) {
    return (
      <button type="button" className={styles.rightIcon} aria-label={props.help} onClick={props.onHelp}>
        <IconFa icon={['far', 'info-circle']} title={props.help} />
      </button>
    )
  }

  return (
    <div className={styles.rightIcon} title={props.help}>
      <IconFa icon={['far', 'info-circle']} />
    </div>
  )
}

function ClearIcon(props: Props) {
  return (
    <button type="button" className={styles.rightIcon} aria-label={props.clear} onClick={props.onClear}>
      <IconFa icon={['far', 'times']} title={props.clear} />
    </button>
  )
}

I would like to check if the input field is active or not. I have tried to do it so:

const active = document.activeElement === ref.current

But, I get following error:

Property 'current' does not exist on type '(instance: HTMLInputElement | null) => void'.

How should I use this forwardedRef correctly?

CodePudding user response:

This is a case where a Component A (here FormInput) accesses the ref prop via a forwardRef, typically to forward it to an inner Component B (here an <input>), but at the same time A needs to refer to B for its internal functionality (here to test its focus).

The issue is that if the consuming parent Component P does not provide any actual reference object to the ref prop of A, ref within A is null. It may also receive a callback ref form (hence the types in the error message).

For such case, you actually need to manage the reference to B internally (useRef in A). And you expose it to P with useImperativeHandle combined with forwardRef, as described e.g. in https://www.carlrippon.com/using-a-forwarded-ref-internally/

import React, { forwardRef, useImperativeHandle, useRef } from 'react'

export const FormInput = forwardRef<HTMLInputElement, Props>(function FormInput(props, forwardedRef) {
  const ref = useRef<HTMLInputElement>(null)

  // Do something internally with the ref...
  console.log(ref.current)

  // Expose the ref externally
  useImperativeHandle<HTMLInputElement | null, HTMLInputElement | null>(
    ref,
    () => internalRef.current
  );

  return (
    <input ref={ref} />
  )
})

CodePudding user response:

Define type for ref like this:

import React, {RefObject } from "react";

ref:
      | RefObject<HTMLInputElement>
      | ((instance: OrNull<HTMLInputElement>) => void)
      | null
  • Related