Created
October 8, 2020 12:42
-
-
Save huguesbr/e8126e5bb21d850ba5d6544080bda2a4 to your computer and use it in GitHub Desktop.
demo of array merge vs override in `react-tracking`
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 } from "react"; | |
import ReactDOM from "react-dom"; | |
import track, { useTracking } from "react-tracking"; | |
import "./styles.css"; | |
// React hooks example | |
const HookButton = () => { | |
const { trackEvent } = useTracking(); | |
return ( | |
<button onClick={() => trackEvent({ event: "hook-usage", values: [4] })}> | |
Hooks example | |
</button> | |
); | |
}; | |
// typical class usage | |
@track({ thing: "thing" }) | |
class Thing extends Component { | |
state = { | |
numClicks: 1 | |
}; | |
// class members usage (with state) | |
@track((props, state) => ({ event: "click", count: state.numClicks, values: [4] })) | |
handleClick = () => { | |
this.setState({ | |
numClicks: this.state.numClicks + 1 | |
}); | |
}; | |
render() { | |
return <button onClick={this.handleClick}>Click me!</button>; | |
} | |
} | |
// ownProps usage | |
@track(({ name }) => ({ page: name, values: [1, 2, 3] })) | |
class Wrapper extends Component { | |
render() { | |
return ( | |
<Fragment> | |
<p> | |
Click, then check the console: <Thing /> | |
</p> | |
<p> | |
React Hooks usage example: <HookButton /> | |
</p> | |
</Fragment> | |
); | |
} | |
} | |
const App = () => ( | |
<div className="App"> | |
<h2> | |
<a href="https://github.com/nytimes/react-tracking">react-tracking</a>{" "} | |
example | |
</h2> | |
<img | |
width="70%" | |
alt="react-tracking logo" | |
src="https://cdn-images-1.medium.com/max/1600/1*DKS5pYfsAz-H45myvnWWVw.gif" | |
/> | |
<Wrapper name="some-wrapper" /> | |
</div> | |
); | |
// functional component usage | |
const TrackedApp = track( | |
// app-level tracking data | |
{ app: "my-app" }, | |
// top-level options | |
{ | |
// custom dispatch to console.log in addition to pushing to dataLayer[] | |
dispatch: data => { | |
console.log(data); | |
(window.dataLayer = window.dataLayer || []).push(data); | |
} | |
} | |
)(App); | |
const rootElement = document.getElementById("root"); | |
ReactDOM.render(<TrackedApp />, rootElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment