React.forwardRef Causes Error with Styled Component
Asked Answered
D

2

6

I am running React 16.3.1 and Styled Components 3.2.5 currently and am hitting an issue trying to use React.forwardRef.

I have an Input component that is comprised of a wrapper div that holds the label and input field. However, I want to be able to forward a ref directly to the input field and not have to traverse to it via the primary wrapping div.

const Input = React.forwardRef((props, ref) => (
  <Wrapper>
    <Label htmlFor={props.id} required={props.required}>
      {props.label}
    </Label>

    <InputField
      id={props.id}
      ...
    />
  </Wrapper>
));

That is a simplified version of my component. However, this creates the following error:

Uncaught Error: Cannot create styled-component for component: [object Object]

Maybe upgrading Styled Components to v4 would help? But is there any solution before upgrading that I haven't found yet?

Thank you.

Doubleheader answered 23/10, 2018 at 7:49 Comment(0)
H
3

As explained in related issue, there is blocking React Redux issue that is expected to be closed with this PR.

A workaround is to use an approach that was used before React 16.3 forwardRef and use custom prop instead of ref to forward refs:

const Input = ({forwardRef, ...props}) => (
  <Wrapper>
    <Label htmlFor={props.id} required={props.required}>
      {props.label}
    </Label>

    <InputField
      ref={forwardRef}
      id={props.id}
      ...
    />
  </Wrapper>
));
Hedonic answered 23/10, 2018 at 9:21 Comment(1)
Thanks a lot! I had to modify your answer slightly since my version of Styled Components still expected ìnnerRef` as opposed to ref. Otherwise, I was able to make this work.Doubleheader
A
-3

Why <Wrapper {...rest}>?

I thing pass ref to Wrapper is a correct way:

<Wrapper ref={ref}>
Acarology answered 23/10, 2018 at 8:6 Comment(1)
Sorry, that was a carry over from old code. Unrelated. But I don't want to put the ref on the Wrapper. I would need it on the Input field.Doubleheader

© 2022 - 2024 — McMap. All rights reserved.