Last active
January 4, 2021 09:54
-
-
Save infinnie/5c30a2c32a826e3f9cdc81c90cc26653 to your computer and use it in GitHub Desktop.
Inject styles like child components
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
var ElementContext = React.createContext(null); | |
class ElementContextComponent extends React.Component { | |
constructor(props) { | |
super(props); | |
this.elementRef = React.createRef(); | |
} | |
render() { | |
return ( | |
<ElementContext.Provider value={{elRef: this.elementRef, styles: {}, timeout: null}}> | |
{this.props.render && this.props.render({ref: this.elementRef})} | |
</ElementContext.Provider> | |
); | |
} | |
} | |
class StyleElement extends React.PureComponent { | |
render() { | |
return ( | |
<ElementContext.Consumer> | |
{(obj) => { | |
if (obj) { | |
Object.assign(obj.styles, this.props.provideStyle); | |
if (!obj.timeout) { | |
obj.timeout = setTimeout(() => { | |
clearTimeout(obj.timeout); | |
obj.timeout = null; | |
console.log("Setting styles"); | |
var el = obj.elRef.current, styles = obj.styles; | |
if (el) { | |
for (var key in styles) { | |
el.style[key] = styles[key]; | |
} | |
} | |
}); | |
} | |
} | |
return null; | |
} | |
}</ElementContext.Consumer> | |
); | |
} | |
} | |
var ElementContextButton = (props) => ( | |
<ElementContextComponent render={({ref}) => ( | |
<button type="button" ref={ref}>{props.children}</button> | |
)} /> | |
); | |
var Transform = () => (<StyleElement provideStyle={{transform: "rotate(30deg)"}} />); | |
var Filter = () => (<StyleElement provideStyle={{filter: "blur(3px)"}} />); | |
ReactDOM.render(<ElementContextButton> | |
<Transform /> | |
<Filter /> | |
Hello | |
</ElementContextButton>, document.getElementById("app")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment