2

When wrapping my styled component in connectDragSource I get the following error:

Uncaught Error: Only native element nodes can now be passed to React DnD connectors.You can either wrap PaneItemText__StyledItem into a <div>, or turn it into a drag source or a drop target itself.

The first suggestion from this message is to wrap my styled component in a <div>, but this will mess with my layout and would prefer not to do this. I'm not sure what the second option is suggesting - would anybody be able to clarify?

Below is an rough example what I am doing:

import React, { Component } from 'react';
import styled from 'styled-components';
import { DragSource } from 'react-dnd';

const StyledComponent = syled.div`
...
`;

class MyComponent extends Component {
    ...
    render() {
        const { connectDragSource } = this.props;
        return connectDragSource(<StyledComponent />)
    }
}

const itemSource = {
    beginDrag(props) {
        /* code here */
    },
    endDrag(props) {
        /* code here */
    }
};

function collect(connect, monitor) {
    return {
        connectDragSource: connect.dragSource(),
        isDragging: monitor.isDragging()
    }
}

export default DragSource('foo', itemSource, collect(MyComponent);
JoeTidee
  • 24,754
  • 25
  • 104
  • 149

2 Answers2

5

You should use Styled Component's innerRef to get the underlying DOM node, then you can call your connectDragSource to it.

In your case, it should be like this:

class MyComponent extends Component {
...
    render() {
        const { connectDragSource } = this.props;
        return (
            <StyledComponent
                innerRef={instance => connectDragSource(instance)}
            />
        )
    }
}

You can also look at my implementation of Knight component for the official chess tutorial as a reference. It is also accessible through CodeSandbox.

Zain
  • 339
  • 2
  • 9
  • What if you don't need any connectDragSource? For example using styled-components on DragLayer. – Radu Dec 02 '19 at 14:53
3

If you are using multiple connectors you can do the following:

<MyStyledComponent
  innerRef={instance => {
    connectDragSource(instance);
    connectDropTarget(instance);
  }}
/>

Source: https://github.com/react-dnd/react-dnd/issues/347#issuecomment-221703726

Darkowic
  • 661
  • 8
  • 17