Is it possible to do a cloneNode in React?
At its basic level, what I wanted to do was click on the ponent, and then have it make a copy of that ponent for me to use. I eventually want to do a simple copy drag and then drop but I just wanted to know how to do a clone of the ponent/element.
Is there a better way to go about this? The ponent will be static, and then a simple click would clone it or dynamically created for use.
var TestChild = React.createClass({
onClick: function (e) {
this.props.onClick(e);
},
render: function () {
return (
<div onClick={this.onClick}>Test Item</div>
)
}
});
var TestParent = React.createClass({
onClick: function (e) {
// cloneNode
},
render: function () {
return (
<TestChild onClick={this.onClick} />
)
}
});
Is it possible to do a cloneNode in React?
At its basic level, what I wanted to do was click on the ponent, and then have it make a copy of that ponent for me to use. I eventually want to do a simple copy drag and then drop but I just wanted to know how to do a clone of the ponent/element.
Is there a better way to go about this? The ponent will be static, and then a simple click would clone it or dynamically created for use.
var TestChild = React.createClass({
onClick: function (e) {
this.props.onClick(e);
},
render: function () {
return (
<div onClick={this.onClick}>Test Item</div>
)
}
});
var TestParent = React.createClass({
onClick: function (e) {
// cloneNode
},
render: function () {
return (
<TestChild onClick={this.onClick} />
)
}
});
Share
Improve this question
asked Jul 15, 2016 at 14:49
fesfes
2,52511 gold badges40 silver badges58 bronze badges
1
-
1
React has
cloneElement
method - facebook.github.io/react/docs/…, you can try use it – Oleksandr T. Commented Jul 15, 2016 at 14:54
2 Answers
Reset to default 0What about keeping a state in parent element TestParent
denoting how many child element TestChild
now should be there, like this.state.count
, then in parent's render
method, map the state to TestChild
s. And the onClick
function just increment the counter. Here is an example from the React docs
I do not really understand what you want to do exactly but what about referencing your child ponent and then using cloneElement(), so something like this.
var TestChild = React.createClass({
onClick: function (e) {
this.props.onClick(e);
},
render: function () {
return (
<div onClick={this.onClick}>Test Item</div>
)
}
});
var TestParent = React.createClass({
onClick: function (e) {
const newEl = React.cloneElement(this.myRef, {});
// then you do whatever you need to do with your new copy of TestChild ponent
},
render: function () {
return (
<TestChild onClick={this.onClick} ref={this.myRef} />
)
}
});
Maybe this helps?