Created
March 5, 2018 00:53
-
-
Save EdwardIrby/16606f39d7ecc711ed4b6598a5539999 to your computer and use it in GitHub Desktop.
A little Web Component in my React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component, Fragment, Children } from 'react'; | |
import { render, unmountComponentAtNode } from 'react-dom'; | |
import PropTypes from 'prop-types'; | |
export class ShadowDom extends Component { | |
constructor(props){ | |
super(props) | |
this.getTargetRef = this.getTargetRef.bind(this); | |
} | |
componentDidMount() { | |
const { children, delegatesFocus } = this.props; | |
this.shadowRoot = this.target.attachShadow({ mode: 'open', delegatesFocus }); | |
render(<Fragment>{ children }</Fragment>, this.shadowRoot) | |
} | |
componentDidUpdate() { | |
const { children } = this.props; | |
render(<Fragment>{ children }</Fragment>, this.shadowRoot); | |
} | |
componentWillUnmount() { | |
unmountComponentAtNode(this.shadowRoot); | |
} | |
getTargetRef(c) { | |
const { nodeRef } = this.props; | |
this.target = c; | |
nodeRef && nodeRef(c); | |
} | |
render() { | |
// Don't pass children and delegatesFocus with spread. | |
const { tag, delegatesFocus, children, lightDom, ...rest } = this.props; | |
const ShadowDomTag = tag; | |
return ( | |
<ShadowDomTag ref={ this.getTargetRef } { ... rest }> | |
{ lightDom() } | |
</ShadowDomTag> | |
); | |
} | |
} | |
ShadowDom.propTypes = { | |
tag: PropTypes.string, | |
delegatesFocus: PropTypes.bool, | |
nodeRef: PropTypes.func, | |
lightDom: PropTypes.func, | |
} | |
ShadowDom.defaultProps = { | |
tag: 'span', | |
delegatesFocus: false, | |
lightDom: () => null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment