Skip to content

Instantly share code, notes, and snippets.

@renanpvaz
Last active April 26, 2020 21:37
Show Gist options
  • Save renanpvaz/8eb8d9fc9a402ecf7274b7f360461cd8 to your computer and use it in GitHub Desktop.
Save renanpvaz/8eb8d9fc9a402ecf7274b7f360461cd8 to your computer and use it in GitHub Desktop.
React component that prevents a child element from having it's styles altered
import React, { useState, useEffect } from 'react'
const findByAttr = (attr, mutations) => mutations.find(m => m.attributeName === attr)
const isBlockerTarget = mutation => 'intransigentBlockerTarget' in mutation.target.dataset
const IntransigentBlocker = props => {
const [id] = useState(+new Date)
useEffect(() => {
const observer = new MutationObserver(mutations => {
const styleMutation = findByAttr('style', mutations)
const target = findByAttr('data-intransigent-blocker-target', mutations)
if (styleMutation && isBlockerTarget(styleMutation)) {
styleMutation.target.style.filter = 'blur(6px)'
console.log('styleMutation', styleMutation)
}
if (target && !isBlockerTarget(target)) {
target.target.dataset.intransigentBlockerTarget = true
console.log('target', target)
}
})
observer.observe(document.getElementById(id), {
attributes: true,
childList: true,
subtree: true
})
})
return (
<div id={id}>
{props.children}
</div>
)
}
export default IntransigentBlocker
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment