ensure-forward-ref-using-ref
Rule category
Correctness.
What it does
Requires that components wrapped with forwardRef
must have a ref
parameter.
This rule checks all React components using forwardRef
and verifies that there is a second parameter.
Why is this bad?
Omitting the ref
argument is usually a bug, and components not using ref
don’t need to be wrapped by forwardRef
.
Examples
Failing
import React from "react";
const const Example: React.ForwardRefExoticComponent<React.RefAttributes<unknown>>
Example = React.function React.forwardRef<unknown, {}>(render: React.ForwardRefRenderFunction<unknown, {}>): React.ForwardRefExoticComponent<React.PropsWithoutRef<{}> & React.RefAttributes<unknown>>
Lets your component expose a DOM node to a parent component
using a ref.forwardRef((props: {}
props) => {
// - 'forwardRef' is used with this component but no 'ref' parameter is set.
return <JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>
button />;
});
Passing
import React from "react";
const const Example: React.ForwardRefExoticComponent<React.RefAttributes<HTMLButtonElement>>
Example = React.function React.forwardRef<HTMLButtonElement, {}>(render: React.ForwardRefRenderFunction<HTMLButtonElement, {}>): React.ForwardRefExoticComponent<React.PropsWithoutRef<{}> & React.RefAttributes<HTMLButtonElement>>
Lets your component expose a DOM node to a parent component
using a ref.forwardRef<HTMLButtonElement>((props: {}
props, ref: React.ForwardedRef<HTMLButtonElement>
ref) => {
return <JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>
button React.RefAttributes<HTMLButtonElement>.ref?: React.LegacyRef<HTMLButtonElement> | undefined
Allows getting a ref to the component instance.
Once the component unmounts, React will set `ref.current` to `null`
(or call the ref with `null` if you passed a callback ref).ref={ref: React.ForwardedRef<HTMLButtonElement>
ref} />;
});