Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add overwrite property #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 38 additions & 21 deletions src/meta_tags.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,25 @@ class MetaTags extends Component {
static contextTypes = {
extract: PropTypes.func
}
getChildren() {
if(!this.props.overwrite) return this.props.children;

return React.Children.map(this.props.children, child => React.cloneElement(child, {
'data-source': 'react-meta-tags'
})
)
}
extractChildren() {
const {extract} = this.context;

if (extract) {
extract(this.props.children);
extract(this.getChildren());
return;
}
}
handleChildrens() {
const {children} = this.props;
const {overwrite} = this.props;
const children = this.getChildren();

if (this.context.extract){
return;
Expand All @@ -61,26 +70,34 @@ class MetaTags extends Component {
const head = document.head;
const headHtml = head.innerHTML;

//filter children remove if children has not been changed
childNodes = childNodes.filter((child) => {
return headHtml.indexOf(getDomAsString(child)) === -1;
});

//remove title and elements from head tag having same id
childNodes.forEach((child) => {
const elemInHead = !!child.id && head.querySelector('#' + child.id);
if (elemInHead) {
head.removeChild(elemInHead);
}

//remove title always
if(!elemInHead && child.tagName === 'TITLE'){
const title = head.querySelector('title');
if(title) {
head.removeChild(title);
if(overwrite) {
const nodes = Array.prototype.slice.call(head.querySelectorAll('[data-source=react-meta-tags]'));

nodes.forEach((node) => {
head.removeChild(node)
});
} else {
//filter children remove if children has not been changed
childNodes = childNodes.filter((child) => {
return headHtml.indexOf(getDomAsString(child)) === -1;
});

//remove title and elements from head tag having same id
childNodes.forEach((child) => {
const elemInHead = !!child.id && head.querySelector('#' + child.id);
if (elemInHead) {
head.removeChild(elemInHead);
}
}
});

//remove title always
if(!elemInHead && child.tagName === 'TITLE'){
const title = head.querySelector('title');
if(title) {
head.removeChild(title);
}
}
});
}

appendChild(document.head, childNodes);
}
Expand Down