In my react componentDidMount
I get meta tags from the response that needs to be added before the </head>
. The problem is that I need to remove the meta tags when the component unmounts. I saw a solution to add an ID so I can do getElementById and remove it that way but since the meta tags are dynamic unless the person adding them in the response adds them manually it won’t work for this case. Is there a way to do this?
componentDidMount() { if (this.props.headerContent { return window.document.createRange().createContextualFragment(this.props.headerContent); } }
The sample response can be something like this
<meta name=test123> <meta name=test242>
this requires a node to work unfortunately
window.document.head.removeChild();
Advertisement
Answer
createContextualFragment()
is creating a DocumentFragment.
Before you return it from componentDidMount()
you could loop over its .children
and either add an attribute like a class
you can later look up, or just store a reference to those nodes somewhere so you can later remove them.
For example (not tested):
// in componentDidMount const fragment = window.document.createRange().createContextualFragment(this.props.headerContent); for (const child of fragment.children) { child.classList.add('managed'); } // in componentWillUnmount window.document.head.querySelectorAll('.managed') .forEach((node) => node.parentElement.removeChild(node));
Instead of using classes you could do something like (also untested):
// in constructor this.managedHeadNodes = []; // in componentDidMount const fragment = window.document.createRange().createContextualFragment(this.props.headerContent); this.managedHeadNodes.push(...fragment.children); // in componentWillUnmount this.managedHeadNodes.forEach((node) => node.parentElement.removeChild(node));