The key is from source code: https://github.com/clauderic/react-sortable-hoc/blob/master/src/SortableElement/index.js#L82
getWrappedInstance() function.
I guess, after is your origin code:
// this is my fake MyElement Component
class MyElement extends React.Component {
render () {
return (
<div className='my-element-example'>This is test my element</div>
)
}
}
// this is your origin ListContainer Component
class OriginListContainer extends React.Component {
render () {
const elements = [
{ childName: 'David' },
{ childName: 'Tom' }
]
return (
<div className='origin-list-container'>
{
elements.map(({ childName }, index) => {
return <MyElement key={index} ref={r => this.refsCollection[childName] = r} />
})
}
</div>
)
}
}
Now you import react-sortable-hoc
import { SortableElement, SortableContainer } from 'react-sortable-hoc'
First you create new Container Component:
const MySortableContainer = SortableContainer(({ children }) => {
return <div>{children}</div>;
})
Then make MyElement be sortable
/**
* Now you have new MyElement wrapped by SortableElement
*/
const SortableMyElement = SortableElement(MyElement, {
withRef: true
})
Here is import:
- You should use
SortableElement(MyElement, ... to SortableElement((props) => <MyElement {...props}/>, second plan will make ref prop be null
{ withRef: true } make your can get ref by getWrappedInstance
OK, now you can get your before ref like after ref={r => this.refsCollection[childName] = r.getWrappedInstance()} />
Here is full code:
const MySortableContainer = SortableContainer(({ children }) => {
return <div>{children}</div>;
})
/**
* Now you have new MyElement wrapped by SortableElement
*/
const SortableMyElement = SortableElement(MyElement, {
withRef: true
})
class ListContainer extends React.Component {
refsCollection = {}
componentDidMount () {
console.log(this.refsCollection)
}
render () {
const elements = [
{ childName: 'David' },
{ childName: 'Tom' }
]
return (
<MySortableContainer
axis="xy"
useDragHandle
>
{
elements.map(({ childName }, index) => {
return (
<SortableMyElement
index={index}
key={index}
ref={r => this.refsCollection[childName] = r.getWrappedInstance()} />
)
})
}
</MySortableContainer>
)
}
}
Append
Ehh...
before I said: You should use SortableElement(MyElement, ... to SortableElement((props) => <MyElement {...props}/>, second plan will make ref prop be null
if you really wanna use callback function, you can use like after:
const SortableMyElement = SortableElement(forwardRef((props, ref) => <MyElement ref={ref} {...props} />), {
withRef: true
})
But here NOT the true use of forwardRef
Ehh... choose your wanna.