react-dnd: React 16: Stateless function components cannot be given refs

I’m using the latest dnd v2.5.4 and still getting a console error for calls to DragLayer, which is set up in my app as a stateless function component. This is very similar to #896, which concerned DragDropContext

Log:

warning.js:33 Warning: Stateless function components cannot be given refs. Attempts to access this ref will fail.

Check the render method of `DragLayer(SitePageCustomDragLayer)`.
    in SitePageCustomDragLayer (created by DragLayer(SitePageCustomDragLayer))
    in DragLayer(SitePageCustomDragLayer) (created by SitePageContainer)
    in div (created by PanelBody)
    in PanelBody (created by SitePageContainer)

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 6
  • Comments: 19 (1 by maintainers)

Commits related to this issue

Most upvoted comments

Still, I hope sometime there will be a fix for this issue, but for now using recompose toClass seems like the easiest way (and easiest to get rid of as soon as the issue is resolved). Borrowing @tough-griff example:

import { toClass } from 'recompose';

const wrapInTestContext = (WrappedComponent) => {
  const TestContextWrapper = toClass(props => (
    <Provider store={store}>
      <StaticRouter context={context}>
        <WrappedComponent {...props} />
      </StaticRouter>
    </Provider>
  ));

  return DragDropContext(TestBackend)(TestContextWrapper);
};

You could wrap your functional component with a div and give a ref to that div

What about wrapping it in a React.Fragment component?

I guess you mean something new that was not available at the time when the issue was opened and closed 😉 Because this was added in 16.2.

Digging up old closed issues is not helpful (all 10 participants are pinged / get a notification).

I too am still seeing the Stateless function components cannot be given refs. warning when using the following helper in my tests:

const wrapInTestContext = (WrappedComponent) => {
  const TestContextWrapper = props => (
    <Provider store={store}>
      <StaticRouter context={context}>
        <WrappedComponent {...props} />
      </StaticRouter>
    </Provider>
  );

  return DragDropContext(TestBackend)(TestContextWrapper);
};

Defining TestContextWrapper as a class removes the warning.

#1280 in the recent 7.4.0 made the issue appear for us with DragDropContext

We had DragDropContext decorating a function component, it worked fine so far, and now spits a “Function components cannot be given refs” error.

[edit : for now we’re using the “recompose/toClass” workaround decribed above - it’s a bit of a shame, though 😕 ]

What about wrapping it in a React.Fragment component? It should work.

@bkniffler could you please give an example ?