Examples
Complete working examples for all ad formats in React Native.
๐ Complete App Exampleโ
Full example with all ad types (banner, interstitial, and rewarded):
import React from 'react';
import {
SafeAreaView,
View,
Button,
StyleSheet,
ScrollView,
Text,
} from 'react-native';
import {
initialize,
OcmAdView,
type OcmAdViewHandle,
loadRewarded,
showRewarded,
loadInterstitial,
showInterstitial,
} from 'react-native-ocm-adnetwork-module';
const App = () => {
const bannerRef = React.useRef<OcmAdViewHandle>(null);
const [eventLog, setEventLog] = React.useState<string[]>([]);
const [isRewardedLoaded, setIsRewardedLoaded] = React.useState(false);
const [isInterstitialLoaded, setIsInterstitialLoaded] = React.useState(false);
React.useEffect(() => {
// Initialize SDK on app start
initialize('test_pub_001')
.then(() => logEvent('โ
SDK initialized'))
.catch(error => logEvent(`โ SDK init failed: ${error.message}`));
// Preload interstitial ad
loadInterstitialAd();
// Preload rewarded ad
loadRewardedAd();
}, []);
const logEvent = (message: string) => {
setEventLog(prev => [...prev, `${new Date().toLocaleTimeString()}: ${message}`]);
};
const handleAdEvent = (event) => {
const { type, error } = event.nativeEvent;
logEvent(`Banner: ${type}${error ? ` - ${error}` : ''}`);
};
const reloadBanner = () => {
bannerRef.current?.loadBanner();
logEvent('๐ Reloading banner');
};
const loadRewardedAd = async () => {
try {
await loadRewarded('ca-app-pub-3940256099942544/5224354917');
setIsRewardedLoaded(true);
logEvent('โ
Rewarded ad loaded');
} catch (error) {
logEvent(`โ Rewarded load failed: ${error.message}`);
setIsRewardedLoaded(false);
}
};
const showRewardedAd = async () => {
try {
await showRewarded();
logEvent('๐ User earned reward!');
setIsRewardedLoaded(false);
// Preload next ad
setTimeout(loadRewardedAd, 1000);
} catch (error) {
logEvent(`โ Rewarded show failed: ${error.message}`);
}
};
const loadInterstitialAd = async () => {
try {
await loadInterstitial({
prebidConfigAdId: '1001-sreq-test-300x250-imp-1',
gamAdUnitId: '/75351959/testadunit/test_app_interstitial',
});
setIsInterstitialLoaded(true);
logEvent('โ
Interstitial ad loaded');
} catch (error) {
logEvent(`โ Interstitial load failed: ${error.message}`);
setIsInterstitialLoaded(false);
}
};
const showInterstitialAd = async () => {
try {
await showInterstitial();
logEvent('โ
Interstitial shown');
setIsInterstitialLoaded(false);
// Preload next ad
setTimeout(loadInterstitialAd, 1000);
} catch (error) {
logEvent(`โ Interstitial show failed: ${error.message}`);
}
};
return (
<SafeAreaView style={styles.container}>
<ScrollView contentContainerStyle={styles.scrollContent}>
<Text style={styles.title}>OCM AdNetwork Demo</Text>
{/* Banner Ad */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>Banner Ad</Text>
<OcmAdView
ref={bannerRef}
style={styles.banner}
adUnitId="1001-sreq-test-300x250-imp-1"
refreshInterval={30}
onAdEvent={handleAdEvent}
/>
<Button title="Reload Banner" onPress={reloadBanner} />
</View>
{/* Rewarded Ad */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>Rewarded Ad</Text>
<Button
title={isRewardedLoaded ? 'Show Rewarded Ad' : 'Loading...'}
onPress={showRewardedAd}
disabled={!isRewardedLoaded}
/>
</View>
{/* Interstitial Ad */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>Interstitial Ad</Text>
<Button
title={isInterstitialLoaded ? 'Show Interstitial' : 'Loading...'}
onPress={showInterstitialAd}
disabled={!isInterstitialLoaded}
/>
</View>
{/* Event Log */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>Event Log</Text>
<ScrollView style={styles.log} nestedScrollEnabled>
{eventLog.map((event, index) => (
<Text key={index} style={styles.logText}>
{event}
</Text>
))}
</ScrollView>
</View>
</ScrollView>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#f5f5f5',
},
scrollContent: {
padding: 16,
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 16,
textAlign: 'center',
},
section: {
backgroundColor: 'white',
borderRadius: 8,
padding: 16,
marginBottom: 16,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 4,
elevation: 3,
},
sectionTitle: {
fontSize: 18,
fontWeight: '600',
marginBottom: 12,
},
banner: {
width: 300,
height: 250,
backgroundColor: '#e0e0e0',
alignSelf: 'center',
marginBottom: 12,
},
log: {
maxHeight: 200,
backgroundColor: '#f9f9f9',
borderRadius: 4,
padding: 8,
},
logText: {
fontSize: 12,
fontFamily: 'monospace',
marginBottom: 4,
},
});
export default App;
๐ฏ Banner Ad Exampleโ
Simple banner ad with manual reload:
import React from 'react';
import { View, Button, StyleSheet } from 'react-native';
import { OcmAdView, type OcmAdViewHandle } from 'react-native-ocm-adnetwork-module';
const BannerExample = () => {
const bannerRef = React.useRef<OcmAdViewHandle>(null);
const handleAdEvent = (event) => {
console.log('Ad event:', event.nativeEvent);
};
const reloadBanner = () => {
bannerRef.current?.loadBanner();
};
return (
<View style={styles.container}>
<OcmAdView
ref={bannerRef}
style={styles.banner}
adUnitId="1001-sreq-test-300x250-imp-1"
refreshInterval={30}
onAdEvent={handleAdEvent}
/>
<Button title="Reload Banner" onPress={reloadBanner} />
</View>
);
};
const styles = StyleSheet.create({
container: {
alignItems: 'center',
gap: 16,
},
banner: {
width: 300,
height: 250,
},
});
๐ Rewarded Ad Exampleโ
Rewarded ad with user reward handling:
import React from 'react';
import { View, Button, Text, StyleSheet } from 'react-native';
import { loadRewarded, showRewarded } from 'react-native-ocm-adnetwork-module';
const RewardedExample = () => {
const [coins, setCoins] = React.useState(100);
const [isLoading, setIsLoading] = React.useState(false);
const watchAd = async () => {
setIsLoading(true);
try {
// Load the ad
await loadRewarded('ca-app-pub-3940256099942544/5224354917');
// Show the ad
await showRewarded();
// Grant reward after ad completes
setCoins(prev => prev + 50);
console.log('๐ User earned 50 coins!');
} catch (error) {
console.error('Rewarded ad error:', error);
alert('Ad not available. Try again later.');
} finally {
setIsLoading(false);
}
};
return (
<View style={styles.container}>
<Text style={styles.coins}>๐ฐ Coins: {coins}</Text>
<Button
title={isLoading ? 'Loading Ad...' : 'Watch Ad (+50 Coins)'}
onPress={watchAd}
disabled={isLoading}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
alignItems: 'center',
gap: 16,
},
coins: {
fontSize: 24,
fontWeight: 'bold',
},
});
๐ฌ Interstitial Ad Exampleโ
Interstitial ad at level completion:
import React from 'react';
import { View, Button, Text, StyleSheet } from 'react-native';
import { loadInterstitial, showInterstitial } from 'react-native-ocm-adnetwork-module';
const GameScreen = () => {
const [level, setLevel] = React.useState(1);
const [adLoaded, setAdLoaded] = React.useState(false);
// Preload interstitial ad
React.useEffect(() => {
loadInterstitialAd();
}, []);
const loadInterstitialAd = async () => {
try {
await loadInterstitial({
prebidConfigAdId: '1001-sreq-test-300x250-imp-1',
gamAdUnitId: '/75351959/testadunit/test_app_interstitial',
});
setAdLoaded(true);
} catch (error) {
console.error('Failed to load interstitial:', error);
setAdLoaded(false);
}
};
const completeLevel = async () => {
// Show ad every 3 levels
if (level % 3 === 0 && adLoaded) {
try {
await showInterstitial();
setAdLoaded(false);
// Preload next ad
setTimeout(loadInterstitialAd, 1000);
} catch (error) {
console.error('Failed to show interstitial:', error);
}
}
// Move to next level
setLevel(prev => prev + 1);
};
return (
<View style={styles.container}>
<Text style={styles.level}>Level {level}</Text>
<Button title="Complete Level" onPress={completeLevel} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
gap: 16,
},
level: {
fontSize: 32,
fontWeight: 'bold',
},
});
๐ฑ Responsive Bannerโ
Banner that adapts to screen size:
import React from 'react';
import { Dimensions, StyleSheet } from 'react-native';
import { OcmAdView } from 'react-native-ocm-adnetwork-module';
const ResponsiveBanner = () => {
const { width } = Dimensions.get('window');
// Calculate banner size (max 300px wide with 16px padding on each side)
const bannerWidth = Math.min(width - 32, 300);
const bannerHeight = (bannerWidth / 300) * 250; // Maintain aspect ratio
return (
<OcmAdView
adUnitId="1001-sreq-test-300x250-imp-1"
style={[
styles.banner,
{
width: bannerWidth,
height: bannerHeight,
},
]}
/>
);
};
const styles = StyleSheet.create({
banner: {
backgroundColor: '#e0e0e0',
},
});
๐จ Custom Ad Containerโ
Banner with loading state and error handling:
import React from 'react';
import { View, Text, ActivityIndicator, StyleSheet } from 'react-native';
import { OcmAdView } from 'react-native-ocm-adnetwork-module';
const AdContainer = () => {
const [adState, setAdState] = React.useState<'loading' | 'loaded' | 'error'>('loading');
const handleAdEvent = (event) => {
const { type } = event.nativeEvent;
if (type === 'loaded') {
setAdState('loaded');
} else if (type === 'failed') {
setAdState('error');
}
};
return (
<View style={styles.container}>
{adState === 'loading' && (
<View style={styles.placeholder}>
<ActivityIndicator size="large" />
<Text>Loading ad...</Text>
</View>
)}
{adState === 'error' && (
<View style={styles.placeholder}>
<Text>Ad unavailable</Text>
</View>
)}
<OcmAdView
adUnitId="1001-sreq-test-300x250-imp-1"
style={[
styles.banner,
adState !== 'loaded' && styles.hidden,
]}
onAdEvent={handleAdEvent}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
width: 300,
height: 250,
},
banner: {
width: 300,
height: 250,
},
hidden: {
opacity: 0,
},
placeholder: {
position: 'absolute',
width: 300,
height: 250,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#e0e0e0',
},
});
๐งช Running the Example Appโ
The module includes a complete example app. To run it:
iOSโ
yarn example ios
Androidโ
yarn example android
The example app demonstrates:
- โ SDK initialization
- โ Banner ads with auto-refresh
- โ Manual banner reload
- โ Rewarded ads with reward handling
- โ Interstitial ads at level completion
- โ Event logging
- โ Error handling
- โ TypeScript integration
Best Practicesโ
1. Preload Adsโ
Preload interstitial and rewarded ads before showing them:
// Preload on mount
React.useEffect(() => {
loadInterstitial({ gamAdUnitId: 'your-unit-id' });
loadRewarded('your-rewarded-unit-id');
}, []);
2. Handle Errorsโ
Always handle errors gracefully:
try {
await showRewarded();
} catch (error) {
// Show fallback content
console.error('Ad error:', error);
}
3. Track Stateโ
Track ad loading state to disable buttons:
const [isLoaded, setIsLoaded] = React.useState(false);
<Button
title="Show Ad"
onPress={showAd}
disabled={!isLoaded}
/>
4. Reload After Showingโ
Reload ads after showing them:
await showInterstitial();
// Preload next ad
setTimeout(() => loadInterstitial({ ... }), 1000);
๐ Supportโ
For support and documentation, contact us at [email protected]
๐ Resourcesโ
- NPM Package: react-native-ocm-adnetwork-module
- GitHub Repository: Check the example project for more details
- License: MIT ยฉ OCM