next.js: ref doesn't work with dynamically imported components
Bug report
Describe the bug
When a component is wrapped in next/dynamic the passed ref should be a ref to the imported component, not an instance of NoSsr or LoadableComponent
To Reproduce
- Import a component using
next/dynamic - Use said component in
renderpassing aref(use a function to received the ref)
Result: the function is called with either a NoSSR component or a LoadableComponent instead of an instance of the component imported in step 1
Expected behavior
The function gets called with an instance of the dynamically loaded component
System information
- Version of Next.js:
6.1.1-canary.4
Additional context
Didn’t try with createRef but it shouldn’t make a difference
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 11
- Comments: 20 (11 by maintainers)
Solution
@juancampa You can use the
forwardRefapi to implement it yourself.pages/index.jscomponents/Component.jsPlease note: You can also omit the
forwardRefapi and pass the ref asforwardedRefin directly.Example
Issues adding this functionality to next.js
I don’t think it makes sense to implement it in next now since:
@matiastucci You have to wrap your component in a custom component and pass the ref through it.
See your modified example: https://codesandbox.io/s/relaxed-pine-b8f5z.
Note that you can use the custom prop way without using
forwardRef(example: https://codesandbox.io/s/busy-jennings-cxll6).If you can’t modify an imported component, then you’ll have to hack into the DOM.
My workaround (or maybe it’s just a forgotten canonical way?) is the following:
Be aware of that if you change your dynamic component due to some conditions, you need to add those conditions to useEffect so the ref is updated with your component.
@fcFn Much appreciated, thanks!
@HaNdTriX what if we want to set ref on the
Componentcomponent itself?Expecting this to be one of the cases for the new
createRefAPISure, here it is:
https://github.com/juancampa/next-bug/blob/master/pages/index.js