mobxjs / mobx-react-lite

Lightweight React bindings for MobX based on React 16.8 and Hooks
https://mobx.js.org/react-integration.html
MIT License
2.13k stars 90 forks source link

forwardRef reports ref as undefined in TS #277

Closed danielkcz closed 4 years ago

danielkcz commented 4 years ago

It's still not possible to use useImperativeHandle with this update, as even with forwardRef:true in observer. Parent components still report ref as being undefined. If I do something like const ImperativeComponent= observer(forwardRef(myComponent)); and export that, it works. But I think this causes issues with memo inside of observer glancing through the code.

Originally posted by @timothyallan in https://github.com/mobxjs/mobx-react-lite/issues/243#issuecomment-615027563

danielkcz commented 4 years ago

@timothyallan Can you please set up a reproduction eg. with CodeSandbox?

danielkcz commented 4 years ago

Could this be fixed be #279?

Sanford284 commented 4 years ago

@FredyC I also appear this problem with function component.

part1

for example:

// parent component
<InfluenceCircle ref={someref} />

// child component
function InfluenceCircle(_props: any, ref: React.RefObject<HTMLDivElement>) {
  return (
    <div ref={ref}></div>
  )
}

export default observer(forwardRef(InfluenceCircle));

It failed. error message like:

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

part2

Also, if I use:

export default forwardRef(observer(InfluenceCircle));

It also failed. error message like

forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))

step is not complex above. if you couldn't reproduction, I will create a codesanbox :)

react: v16.8.3 mobx-react-lite: 2.0.0-alpha.1

danielkcz commented 4 years ago

@yuwanlin Please read the docs, there is forwardRef option you need to use with observer.

And upgrade to the latest 2.0, don't use alpha anymore.

Sanford284 commented 4 years ago

@FredyC It worked. thank you !

export default observer(InfluenceCircle, { forwardRef: true });

mobx-react-lite: 2.0.6