Skip to content

Commit

Permalink
work with elements that have Ref's generated using the Hooks API (#1242)
Browse files Browse the repository at this point in the history
* fix: work with elements that have Ref's generated using the Hooks API

In the new Hooks API, Ref's no longer have to be functions, but can
be simple objects with a `current` property. Instead of calling the
Ref function, React sets `ref.current`.

Currently, the following will throw an error:

```jsx
const MyComponent = ({connectDragSource}) => {
  const ref = useRef();

  return (<div ref={ref}/>);
};

DragSource(type, spec, connect)(MyComponent);
```

There is ongoing work to provide a Hooks API for react-dnd, which will ultimately be preferrable, but this provides an immediate fix for mixing the current API with React Hooks.

* refactor: add setref utility

* feat: add react.createRef to FC simple example
  • Loading branch information
darthtrevino committed Mar 6, 2019
1 parent fd1bae4 commit 4ecc043
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
Expand Up @@ -32,8 +32,13 @@ const Box: React.SFC<BoxProps & BoxCollectedProps> = ({
name,
}) => {
const opacity = isDragging ? 0.4 : 1
const ref = React.createRef()
return connectDragSource
? connectDragSource(<div style={{ ...style, opacity }}>{name}</div>)
? connectDragSource(
<div ref={ref as any} style={{ ...style, opacity }}>
{name}
</div>,
)
: null
}

Expand Down
12 changes: 10 additions & 2 deletions packages/react-dnd/src/utils/cloneWithRef.ts
Expand Up @@ -2,6 +2,14 @@ declare var require: any
import { cloneElement } from 'react'
const invariant = require('invariant')

function setRef(ref: any, node: any) {
if (typeof ref === 'function') {
ref(node)
} else {
ref.current = node
}
}

export default function cloneWithRef(
element: any,
newRef: any,
Expand All @@ -23,9 +31,9 @@ export default function cloneWithRef(

return cloneElement(element, {
ref: (node: any) => {
newRef(node)
setRef(newRef, node)
if (previousRef) {
previousRef(node)
setRef(previousRef, node)
}
},
})
Expand Down

0 comments on commit 4ecc043

Please sign in to comment.