Definitelytyped: StyledComponents, cannot ref

Created on 12 Nov 2018  路  8Comments  路  Source: DefinitelyTyped/DefinitelyTyped

I seem to be unable to ref Styled Components with Typescript. I have asked another user about this and they believe this is a bug so I have decided to file an issue.

private _ref = React.createRef<HTMLDivElement>();

<SliderContainer
  ref={this._ref}
/>
const SliderContainer = styled.div`
  /* whatever */
`

screen_shot_2018-11-11_at_5 44 35_pm

Action: make a styled.div and ref it with React.createRef<HTMLDivElement>()
Expected behavior: it works
Actual behavior: type error, but seems to work with ref={this._ref as any}

All 8 comments

Should be fixed by https://github.com/DefinitelyTyped/DefinitelyTyped/pull/30511
I installed the latest version and it worked fine for me.

/cc @Igorbek @Igmat @Lavoaster to verify

Nope, I still get this error when using the latest version (using React.forwardRef). Can someone testify this too?

Okay, I have tested it is due to {...props} being placed at the last place, probably need something like Omit<React.ComponentProps<'img'>, 'ref'> 馃... If I move it upfront, then the type error disappeared.

Just passing props for divs (or inputs or anything else for that matter) results in a Typescript error because of ref.

https://codesandbox.io/s/styled-components-ref-typescript-error-9hs8t

const StyledFoo = styled.div`
  color: red;
`;

const Foo = (props: JSX.IntrinsicElements['div']) => {
  return <StyledFoo {...props} />;
};

Line 12 there is the error on <StyledFoo {...props} />:

Type '{ ref?: LegacyRef<HTMLDivElement>; key?: Key; defaultChecked?: boolean; defaultValue?: string | string[]; suppressContentEditableWarning?: boolean; suppressHydrationWarning?: boolean; accessKey?: string; ... 247 more ...; onTransitionEndCapture?: (event: TransitionEvent<...>) => void; }' is not assignable to type 'Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "style" | "title" | "children" | "key" | "defaultChecked" | "defaultValue" | "suppressContentEditableWarning" | ... 246 more ... | "onTransitionEndCapture"> & { ...; }, "style" | ... 253 more ... | "onTransitionEndCapture"> & Partial<....'.
  Types of property 'ref' are incompatible.
    Type 'LegacyRef<HTMLDivElement>' is not assignable to type '((instance: HTMLDivElement) => void) | RefObject<HTMLDivElement>'.
      Type 'string' is not assignable to type '((instance: HTMLDivElement) => void) | RefObject<HTMLDivElement>'.ts(2322)

Any updates on this? Still running into this error as well.

it looks I fixed when using this type assertion
const ref = React.useRef() as React.MutableRefObject<HTMLInputElement>

Was this page helpful?
0 / 5 - 0 ratings