0

I get two errors when I try to set ref in react component.

import React from "react";

const Input = React.forwardRef((props, ref) => {
  return <input ref={ref} {...props}/>;
});

export default Input;

Component definition is missing display name eslint(react/display-name).
"Type 'ForwardedRef<unknown>' is not assignable to type 'LegacyRef<HTMLInputElement>'.
  Type 'MutableRefObject<unknown>' is not assignable to type 'LegacyRef<HTMLInputElement>'."

Can you help me?

1 Answer 1

2

forwardRef is a generic. You can tell it what the ref will point to, and what props the component takes. Currently you're not doing so, so the defaults are that the ref is set to unknown, and the props are set to an empty object.

Assuming you want this component to take in all the same props that an <input> can take, you'd fix it like this:

type InputProps = React.DetailedHTMLProps<
  React.InputHTMLAttributes<HTMLInputElement>,
  HTMLInputElement
>;

const Input = React.forwardRef<HTMLInputElement, InputProps>((props, ref) => {
  return <input ref={ref} {...props} />;
});

Component definition is missing display name eslint(react/display-name).

To address this lint error, give the component a display name:

Input.displayName = 'Example';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.