How Can I Create A Wrapper Component For Entire App?
I'm trying to add some analytics tracking for my react app. Basically just using a component to add global event listeners and then handle the event appropriately in that component
Solution 1:
Context API
seems to be your use case here. You want a decoupled way to share data between components in the same tree. Your wrapper could implement a Provider
, and all components that are interest on the shared value will implement a Consumer
. HOC
and render Props
are useful to share stateful logic, not state itself.
const { Provider, Consumer } = React.createContext()
constWrapper = ({children}) =>{
return(
<Providervalue={mySharedValue}>
{children}
</Provider>
)
}
constNestedChildren = () =>{
return(
<Consumer>
{context => <div>{context}</div>}
</Consumer>
)
}
constApp = () =>{
return(
<Wrapper><Child><NestedChild /></Child></Wrapper>
)
}
Solution 2:
We accomplished something like this with react-capture-metrics
.
You provide your analytics API to a top level provider like so:
import { MetricsProvider } from'react-capture-metrics'const analytics = {
track: (name, properties) =>window.analytics.track(name, properties),
page: (name, properties, category) =>window.analytics.page(...(category ? [category, name, properties] : [name, properties]))
}
functionApp () {
return (
<MetricsProvideranalytics={analytics}properties={{appVersion:pkg.version }}>
// ...the rest of your app
</MetricsProvider>
)
}
Then render a PageView
component wherever you want to call analytics.page()
.
functionPage() {
const { PageView } = useMetrics({
variantId,
// ...properties to capture
}, { ready: variantId !== undefined })
return (
<PageViewname="Home"category="Customer"ready={/*someuseStatevalueperhaps */ }
>
// ...
</PageView>
)
}
You can use ready
to delay calling the event until all the properties you want to pass are loaded. Or you can use pageKey
to call the event when the user navigates to the same page but with different params.
Post a Comment for "How Can I Create A Wrapper Component For Entire App?"