react-spring: Is animated(FunctionalComponent) not supported?

Sorry if this has been brought up before! I looked all over the docs and GitHub issues but couldn’t find any mention of this

Is animated(Component) where Component is functional component a known limitation? Here’s a minimal example reproducing the issue: https://codesandbox.io/s/1mp77p57l

It also gives this warning which I assume is relevant

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

But even when attempting to use a simple functional component with React.forwardRef (also done in the example above) it seems to fail silently

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 8
  • Comments: 15 (8 by maintainers)

Commits related to this issue

Most upvoted comments

That used to be a limitation in React before hooks but you still need to opt in essentially. See: https://reactjs.org/docs/hooks-reference.html#useimperativehandle

This seems to work:

const FunctionalComponentWithRef = React.forwardRef(({ color }, ref) => {
  const myRef = React.useRef();
  React.useImperativeHandle(ref, () => ({}));

  return (
    <div
      ref={myRef}
      style={{
        background: color,
        width: 250,
        height: 250
      }}
    />
  );
});

Sorry for letting you wait so long. I hope it’s fixed now. Refs in React are still weird. But i do a simple check now and if it’s a plain function, it doesn’t try to set a reference on it. I hope we can remove this once React throws out forwardRef all together.

@Mathspy That looks quite good, didn’t know about it thanks for digging it up! I will take another look after fixing some issues that were piling up here.

I think we should investigate this further, really weird behaviour

All great questions… actually even this works:

const FunctionalComponentWithRef = React.forwardRef(({ color }, ref) => {
  React.useImperativeHandle(ref, () => ({}));
  return (
    <div
      style={{
        background: color,
        width: 250,
        height: 250
      }}
    />
  );
});

🤷‍♂️

edit: i apologize, clearly didn’t get why it worked. If I test the ref value it does get set to an empty object so React doesn’t seem to be doing anything magic here.