I create a lot of react component dynamically on event handle. The code is given blow:
var node = []; //this is update with properties on user action and an element is creaed
var node = Interfaces.Embroidery.node;
var components = node.map(function(props) {
return React.createElement('g', {
id: props.id,
key: props.id
},
React.createElement('path', props));
});
var App = React.createClass({
render: function() {
return React.createElement('div', null, components);
}
});
ReactDOM.render(React.createElement(App), document.getElementById('parentDrawingNode'));
now i want to remove a single element from the dom. i.e it will be a user action component or i want to remove in some special case and other component remain same.
By use refs of we are dealing with actual dom so the refs are not applicable in this case.
You are missing the point of React. You don't manually modify the element tree. You declaratively map properties/state to elements and let React do all of the modifications.
var App = React.createClass({
render: function() {
// Get the node from the passed-in props
var node = this.props.node;
// generate the child components
var components = node.map(function(props) {
return React.createElement('g', {
id: props.id,
key: props.id
},
React.createElement('path', props));
});
// render them in a div
return React.createElement('div', null, components);
}
});
// first time it will create the DOM
// after that it just modifies the DOM
function renderApp(node, element) {
ReactDOM.render(React.createElement(App, { node: node }), element);
}
// Call when you want to get rid of the App completely
// and cleanup memory without reloading the page
function destroyApp(element) {
ReactDOM.unmountComponentAtNode(element);
}
// Initial render
var node = Interfaces.Embroidery.node;
renderApp(node, document.getElementById('parentDrawingNode'));
function updateNodeOnSomeUserActionThatHappensOutsideOfReact(...) {
node.push(...); // or whatever modification you want
// re-render
renderApp(node, document.getElementById('parentDrawingNode'));
}
Read more about this style here: https://facebook.github.io/react/blog/2015/10/01/react-render-and-top-level-api.html
Note this is what you'd do if the "user actions" are occurring outside of your React components (i.e. elsewhere in the app). If the "user actions" occur as events within your React components, you'd only ever call render
once, and instead the App would hold the nodes as state
and would just call this.setState({ node: modifiedNodes });
to change the state, which would cause React to update your DOM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With