|
1 | | -import React from "react"; |
2 | | -import OptimizeContext from "./OptimizeContext"; |
3 | | - |
4 | | -export class Experiment extends React.Component { |
5 | | - static defaultProps = { |
6 | | - loader: null |
7 | | - }; |
8 | | - |
9 | | - state = { |
10 | | - variant: null |
11 | | - }; |
12 | | - |
13 | | - updateVariant = value => { |
14 | | - // if experiment not active, render original |
15 | | - this.setState({ |
16 | | - variant: value === undefined || value === null ? "0" : value |
17 | | - }); |
18 | | - }; |
19 | | - |
20 | | - delayedInitialization = () => { |
21 | | - const value = |
22 | | - window.google_optimize && window.google_optimize.get(this.props.id); |
23 | | - this.updateVariant(value); |
24 | | - }; |
25 | | - |
26 | | - componentDidMount() { |
27 | | - if (!this.props.id) { |
28 | | - throw new Error("Please specify the experiment id"); |
29 | | - } |
30 | | - |
31 | | - // Delayed init |
32 | | - const hideEnd = |
33 | | - window.dataLayer && window.dataLayer.hide && window.dataLayer.hide.end; |
34 | | - if (hideEnd) { |
35 | | - window.dataLayer.hide.end = () => { |
36 | | - this.delayedInitialization(); |
37 | | - hideEnd(); |
38 | | - }; |
39 | | - } else { |
40 | | - this.delayedInitialization(); |
41 | | - } |
42 | | - |
43 | | - window.gtag && window.gtag("event", "optimize.callback", { |
44 | | - name: this.props.id, |
45 | | - callback: this.updateVariant |
46 | | - }); |
47 | | - } |
48 | | - |
49 | | - componentWillUnmount() { |
50 | | - window.gtag && window.gtag("event", "optimize.callback", { |
51 | | - name: this.props.id, |
52 | | - callback: this.updateVariant, |
53 | | - remove: true |
54 | | - }); |
55 | | - } |
56 | | - |
57 | | - render() { |
58 | | - return ( |
59 | | - <OptimizeContext.Provider value={this.state.variant}> |
60 | | - {this.state.variant === null ? this.props.loader : this.props.children} |
61 | | - </OptimizeContext.Provider> |
62 | | - ); |
63 | | - } |
64 | | -} |
65 | | - |
66 | | -export class Variant extends React.Component { |
67 | | - render() { |
68 | | - return ( |
69 | | - <OptimizeContext.Consumer> |
70 | | - {value => (value === this.props.id ? this.props.children : null)} |
71 | | - </OptimizeContext.Consumer> |
72 | | - ); |
73 | | - } |
74 | | -} |
75 | | - |
76 | | -export default { |
77 | | - Experiment, |
78 | | - Variant |
79 | | -}; |
| 1 | +export { default as Experiment } from "./Experiment"; |
| 2 | +export { default as Variant } from "./Variant"; |
0 commit comments