Reputation: 2512
https://github.com/mzabriskie/react-draggable
How can I get a custom component to drag?
The following works when clicked
import React from 'react';
import { DraggableCore } from 'react-draggable';
export default class Hello extends React.Component {
onStart = () => {
console.log('here');
}
render() {
return (
<DraggableCore
onStart={this.onStart}
>
<h1>Drag me!</h1>
</DraggableCore>
);
}
}
and this does not
import React from 'react';
import { DraggableCore } from 'react-draggable';
class Test extends React.Component {
render() {
return (
<h1>{this.props.children}</h1>
);
}
}
export default class Hello extends React.Component {
onStart = () => {
console.log('here');
}
render() {
return (
<DraggableCore
onStart={this.onStart}
>
<Test>Drag me!</Test>
</DraggableCore>
);
}
}
with the only difference being that instead of h1
being used directly, it now uses custom component Test
https://stackblitz.com/edit/react-ev9iyu?file=Hello.js
I have tried forwarding the ref. I have also tried wrapping it in a Fragment
Upvotes: 2
Views: 8488
Reputation: 21
I'm super late to the game here but I hope this helps someone. You have to give your component a rest prop. You need to do this because DraggableCore copies the component and puts several event listeners on the component. Look at the render of DraggableCore. https://github.com/react-grid-layout/react-draggable/blob/master/lib/DraggableCore.js. Your component needs to be able to receive these event listeners.
const Test = ({ children, ...rest }) => {
return (
<div {...rest}>{children}</div>
)
}
const Hello = () => {
const handleStart = () => console.log('here');
return (
<DraggableCore
onStart={handleStart}
>
<Test>Drag me!</Test>
</DraggableCore>
);
}
Upvotes: 2
Reputation: 19782
Wrap your component with a div
inside of DraggableCore
:
<DraggableCore onStart={this.onStart}>
<div>
<Test>Drag me!</Test>
</div>
</DraggableCore>
Upvotes: 4