Last active
August 29, 2019 10:18
-
-
Save cevek/4ac63323a15cafe2d37b5c916ac7804f to your computer and use it in GitHub Desktop.
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 * as React from 'react'; | |
import * as ReactDom from 'react-dom'; | |
type ZoneContext = {name: string; params?: {}; parent: ZoneContext | null; children: ZoneContext[]}; | |
const Context = React.createContext<ZoneContext | null>(null); | |
function useMetrika(someData?: {}) { | |
const context = React.useContext(Context); | |
const parents: ZoneContext[] = []; | |
if (context !== null) { | |
let ctx = context; | |
parents.push(ctx); | |
while (ctx.parent) { | |
ctx = ctx.parent; | |
parents.push(ctx); | |
} | |
} | |
const zoneNames = parents.map(zone => zone.name); | |
return () => { | |
const rootZone = parents[parents.length - 1]; | |
console.log('click', zoneNames, someData, rootZone); | |
}; | |
} | |
function App() { | |
return ( | |
<Context.Provider value={null}> | |
<Zone name="root"> | |
<Zone name="button1"> | |
<Button /> | |
</Zone> | |
<Zone name="button2"> | |
<Button /> | |
</Zone> | |
</Zone> | |
</Context.Provider> | |
); | |
} | |
function Button(props: {}) { | |
const send = useMetrika('Hello'); | |
return <button onClick={send}>Click me</button>; | |
} | |
function Zone(props: {children: JSX.Element | JSX.Element[]; name: string; params?: {}}) { | |
const parent = React.useContext(Context); | |
const context: ZoneContext = {name: props.name, params: props.params, children: [], parent}; | |
if (parent !== null) { | |
parent.children.push(context); | |
} | |
return <Context.Provider value={context}>{props.children}</Context.Provider>; | |
} | |
ReactDom.render(<App />, document.getElementById('root')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment