Skip to content

Instantly share code, notes, and snippets.

@infinnie
Last active January 4, 2021 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save infinnie/5c30a2c32a826e3f9cdc81c90cc26653 to your computer and use it in GitHub Desktop.
Save infinnie/5c30a2c32a826e3f9cdc81c90cc26653 to your computer and use it in GitHub Desktop.
Inject styles like child components
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