UNPKG

1.71 kBJavaScriptView Raw
1/* @flow */
2
3import React from 'react';
4import { requireNativeComponent } from 'react-native';
5import { EmitterSubscription } from 'fbemitter';
6import AdsManager from './NativeAdsManager';
7import type { NativeAd } from './types';
8
9const NativeAdView = requireNativeComponent('CTKNativeAd', null);
10
11type NativeAdWrapperState = {
12 ad: ?NativeAd,
13 canRequestAds: boolean,
14};
15
16type NativeAdWrapperProps = {
17 adsManager: AdsManager,
18};
19
20/**
21 * Higher order function that wraps given `Component` and provides `nativeAd` as a prop
22 *
23 * In case of an empty ad or adsManager not yet ready for displaying ads, null will be
24 * returned instead of a component provided.
25 */
26export default (Component: Function) => class NativeAdWrapper extends React.Component {
27 state: NativeAdWrapperState = {
28 ad: null,
29 canRequestAds: false,
30 };
31
32 props: NativeAdWrapperProps;
33
34 /** @{EmitterSubscription} **/
35 subscription: EmitterSubscription;
36
37 /**
38 * On init, register for updates on `adsManager` to know when it becomes
39 * available for accessing
40 */
41 componentDidMount() {
42 this.subscription = this.props.adsManager.onAdsLoaded(
43 () => this.setState({ canRequestAds: true })
44 );
45 }
46
47 /**
48 * Clear subscription when component goes off screen
49 */
50 componentWillUnmount() {
51 this.subscription.remove();
52 }
53
54 render() {
55 const { adsManager, ...props } = this.props;
56
57 if (!this.state.canRequestAds) {
58 return null;
59 }
60
61 return (
62 <NativeAdView
63 adsManager={adsManager.toJSON()}
64 onAdLoaded={(e) => this.setState({ ad: e.nativeEvent })}>
65 {this.state.ad && <Component nativeAd={this.state.ad} {...props} />}
66 </NativeAdView>
67 );
68 }
69};