Skip to content

Commit ec6da80

Browse files
committed
Reusing child component
1 parent 7ac7840 commit ec6da80

File tree

2 files changed

+28
-11
lines changed

2 files changed

+28
-11
lines changed

lib/draggable.js

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1+
'use strict';
2+
13
/** @jsx React.DOM */
2-
var React = require('react'),
4+
var React = require('react/addons'),
5+
invariant = require('react/lib/invariant'),
36
emptyFunction = require('react/lib/emptyFunction');
47

58
function createUIEvent(draggable) {
@@ -22,6 +25,8 @@ function canDragX(draggable) {
2225
}
2326

2427
module.exports = React.createClass({
28+
displayName: 'Draggable',
29+
2530
propTypes: {
2631
/**
2732
* `axis` determines which axis the draggable can move.
@@ -112,6 +117,13 @@ module.exports = React.createClass({
112117
};
113118
},
114119

120+
componentWillMount: function () {
121+
invariant(
122+
React.Children.count(this.props.children) === 1,
123+
'There should only be a single child element within Draggable.'
124+
);
125+
},
126+
115127
handleMouseDown: function (e) {
116128
var node = this.getDOMNode();
117129
this.setState({
@@ -147,13 +159,20 @@ module.exports = React.createClass({
147159
left: canDragX(this) ? this.state.clientX : this.state.startX
148160
};
149161

150-
return (
151-
<div style={style}
152-
className="react-draggable"
153-
onMouseUp={this.handleMouseUp}
154-
onMouseDown={this.handleMouseDown}>
155-
{this.props.children}
156-
</div>
157-
);
162+
// Reuse the child provided
163+
// This makes it flexible to use whatever element is wanted (div, ul, etc)
164+
var child = null;
165+
React.Children.forEach(this.props.children, function (c) {
166+
if (child === null) {
167+
child = React.addons.cloneWithProps(c, {
168+
style: style,
169+
className: 'react-draggable',
170+
onMouseUp: this.handleMouseUp,
171+
onMouseDown: this.handleMouseDown
172+
});
173+
}
174+
}, this);
175+
176+
return child;
158177
}
159178
});

lib/styles.css

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
.react-draggable {
2-
cursor: move;
3-
display: inline-block;
42
position: relative;
53
-webkit-user-select: none;
64
-moz-user-select: none;

0 commit comments

Comments
 (0)