### Start Application on iOS (npm/Yarn)
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/example/README.md
Launches the React Native application on an iOS simulator or connected device. This command is run after the Metro server has started.
```bash
# using npm
npm run ios
# OR using Yarn
yarn ios
```
--------------------------------
### Start Metro Server (npm/Yarn)
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/example/README.md
Starts the Metro JavaScript bundler, essential for React Native development. This command should be run from the root of the React Native project.
```bash
# using npm
npm start
# OR using Yarn
yarn start
```
--------------------------------
### Start Application on Android (npm/Yarn)
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/example/README.md
Launches the React Native application on an Android emulator or connected device. This command is run after the Metro server has started.
```bash
# using npm
npm run android
# OR using Yarn
yarn android
```
--------------------------------
### Clone and Run Example App
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/examples.md
This snippet demonstrates how to clone the project repository and run the example application on an Android device. Ensure you have React Native development environment set up.
```bash
git clone https://github.com/ammarahm-ed/react-native-admob-native-ads.git
cd react-native-admob-native-ads
yarn install
cd example
yarn install
# For Android
yarn react-native run-android
# For iOS
yarn react-native run-ios
```
--------------------------------
### Start Local Development Server
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/README.md
Starts a local development server for the Docusaurus website. Changes are reflected live without server restarts, facilitating rapid development.
```console
yarn start
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/README.md
Installs the necessary dependencies for the project using Yarn. This is a prerequisite for local development and building.
```console
yarn install
```
--------------------------------
### Install react-native-vector-icons (npm/yarn)
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/installation.mdx
Install the react-native-vector-icons package, which is a dependency for using the StarRatingView component. This can be done using npm or yarn.
```bash
npm install react-native-vector-icons --save
```
```bash
yarn add react-native-vector-icons
```
--------------------------------
### Install react-native-admob-native-ads (npm/yarn)
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/installation.mdx
Install the react-native-admob-native-ads package using either npm or yarn. This is the first step for integrating AdMob native ads into your React Native application.
```bash
npm install react-native-admob-native-ads --save
```
```bash
yarn add react-native-admob-native-ads
```
--------------------------------
### Update Podfile for Google Mobile Ads SDK
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/migrating.md
Update your Podfile to include the latest Google Mobile Ads SDK and the Facebook mediation adapter. After updating the Podfile, run 'pod update' and 'pod install'. For existing installations, use 'pod install --repo-update'.
```ruby
pod 'Google-Mobile-Ads-SDK'
pod 'GoogleMobileAdsMediationFacebook'
```
--------------------------------
### Register Ad Repository for Preloading
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/nativeadview/nativeadview.md
Provides an example of registering an ad repository using `AdManager.registerRepository`. This allows for preloading ads to improve user experience by avoiding load times.
```javascript
AdManager.registerRepository({
name: 'imageAd',
adUnitId: NATIVE_AD_ID,
numOfAds: 3,
nonPersonalizedAdsOnly: false,
videoOptions: {
mute: false,
},
expirationPeriod: 3600000, // in milliseconds (optional)
mediationEnabled: false,
}).then(result => {
console.log('registered: ', result);
});
```
--------------------------------
### iOS Podfile Configuration for AdMob
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/installation.mdx
Include the Google Mobile Ads SDK in your iOS project's Podfile. This step is necessary for integrating AdMob ads on iOS.
```ruby
pod 'Google-Mobile-Ads-SDK', '~>9.11.0'
```
--------------------------------
### Basic NativeAdView Usage
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/nativeadview/nativeadview.md
Shows a fundamental example of using the NativeAdView component. It requires an 'adUnitID' prop and wraps other ad-related components.
```jsx
/* All other ad components */
```
--------------------------------
### Expo Configuration for AdMob Native Ads
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/installation.mdx
Configure AdMob App IDs for Android and iOS within your Expo project's app.json or app.config.js file. This setup is essential for Expo applications using the react-native-admob-native-ads library.
```json
{
"expo": {
"plugins": [
[
"react-native-admob-native-ads",
{
"androidAppId": "ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy",
"iosAppId": "ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy",
"facebookMediation": false
}
]
]
}
}
```
--------------------------------
### Manually Load Ads with NativeAdView Ref
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/migrating.md
Demonstrates how to manually load ads using the `ref` prop on the `NativeAdView` component. Each `NativeAdView` requires a unique ref. The `loadAd()` method is called within a `useEffect` hook to ensure the ad is loaded when the component mounts.
```jsx
const AdView = () => {
// Each NativeAdView component needs to have its own ref, you cannot use the same ref for multiple ads.
const nativeAdViewRef = useRef();
React.useEffect(() => {
nativeAdViewRef.current?.loadAd();
}, []);
return (
/* All other ad components */
);
};
```
--------------------------------
### Android Manifest Configuration for AdMob
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/installation.mdx
Add your AdMob App ID to the AndroidManifest.xml file for your application. This configuration is required by the Google Mobile Ads SDK for Android.
```xml
```
--------------------------------
### Render Star Rating View using react-native-admob-native-ads
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/components/star.md
This snippet demonstrates how to import and use the StarRatingView component from the 'react-native-admob-native-ads' library. This component is responsible for displaying star ratings, typically for apps listed on Google Play or the App Store. No specific props are shown in this basic example, but it serves as the entry point for rendering the star rating UI.
```jsx
import { StarRatingView } from "react-native-admob-native-ads";
```
--------------------------------
### Enable Test Device in react-native-admob-native-ads
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/installation.mdx
Register a test device for debugging AdMob ads within your React Native application using the AdManager. Ensure you replace 'Your test device id' with the actual ID obtained from your device.
```javascript
import {AdManager} from "react-native-admob-native-ads";
AdManager.setRequestConfiguration({
testDeviceIds:["Your test device id"];
});
```
--------------------------------
### Deploy Website to GitHub Pages
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/README.md
Builds the website and deploys it to the 'gh-pages' branch, specifically for hosting on GitHub Pages. Requires setting the GIT_USER environment variable and optionally using SSH.
```console
GIT_USER= USE_SSH=true yarn deploy
```
--------------------------------
### Build Static Website Content
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/README.md
Generates the static content for the website, typically placed in a 'build' directory. This content can then be hosted on any static hosting service.
```console
yarn build
```
--------------------------------
### Targeting Options
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/nativeadview/targetingoptions.md
This section details the various targeting options available for ad requests, including their types, requirements, and descriptions.
```APIDOC
## Targeting Options
### Description
This section details the various targeting options available for ad requests, including their types, requirements, and descriptions.
### Parameters
#### Request Body
- **publisherProvidedID** (string) - Optional - Publisher provided user ID.
- **categoryExclusions** (Array) - Optional - Array of strings used to exclude specified categories in ad results.
- **targets** (Array) - Optional - Key-value pairs used for custom targeting. `Target:{ key: boolean, value: string | Array }`
- **requestAgent** (string) - Optional - String that identifies the ad request’s origin. Third party libraries that reference the Mobile Ads SDK should set this property to denote the platform from which the ad request originated.
- **keywords** (Array) - Optional - Array of keyword strings. Keywords are words or phrases describing the current user activity such as “Sports Scores” or “Football”.
- **contentUrl** (string) - Optional - URL string for a webpage whose content matches the app’s primary content. This webpage content is used for targeting and brand safety purposes.
- **neighboringContentUrls** (Array) - Optional - URL strings for non-primary web content near an ad. Promotes brand safety and allows displayed ads to have an app level rating (MA, T, PG, etc) that is more appropriate to neighboring content.
### Request Example
```json
{
"publisherProvidedID": "user123",
"categoryExclusions": ["sports", "news"],
"targets": [
{"key": true, "value": "college"}
],
"requestAgent": "CoolAds",
"keywords": ["football", "scores"],
"contentUrl": "http://www.example.com/article",
"neighboringContentUrls": ["http://www.example.com/related1", "http://www.example.com/related2"]
}
```
### Response
#### Success Response (200)
No specific response body defined for this configuration section. The effects are on the ad request itself.
```
--------------------------------
### NativeAdView - Basic Props
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/nativeadview/props.md
Configuration options for NativeAdView.
```APIDOC
## NativeAdView Props
This section details the basic props that can be used to configure the `NativeAdView` component.
### `style`
* **Description**: Allows custom styling for the `NativeAdView`.
* **Type**: `object`
* **Required**: No
### `adUnitID`
* **Description**: The Ad Unit ID for Native Advanced Ads from your AdMob account. Use test IDs during development.
* **Type**: `string`
* **Required**: Yes
* **Platform**: All
### `enableTestMode`
* **Description**: When set to `true`, loads a placeholder ad for easier design, especially without internet. Set `adUnitID` to `null` when using this.
* **Type**: `boolean`
* **Required**: No
* **Platform**: All
### `adChoicesPlacement`
* **Description**: Determines the placement of the AdChoices icon on the ad. Defaults to `topRight`.
* **Type**: `enum` (topLeft, topRight, bottomLeft, bottomRight)
* **Required**: No
* **Default**: `topRight`
### `mediaAspectRatio`
* **Description**: Specifies the preferred aspect ratio for media content in the ad. Defaults to `any`.
* **Type**: `enum` (unknown, any, landscape, portrait, square)
* **Required**: No
* **Default**: `any`
### `requestNonPersonalizedAdsOnly`
* **Description**: Set to `true` to comply with Google EU User Consent Policy, serving non-personalized ads. Requires user consent management.
* **Type**: `boolean`
* **Required**: No
* **Platform**: All
```
--------------------------------
### Repository API
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/admanager/repository.md
This section details the methods for managing ad repositories, including registration, unregistration, cache resetting, and checking ad availability.
```APIDOC
## Repository Management API
Repositories allow for preloading ads to be shown to users within the app.
### `registerRepository`
Register a repository to preload ads.
#### Parameters
##### Request Body
- **name** (string) - Optional - The name of the repository.
- **adUnitId** (string) - Required - The AdMob ad unit ID.
- **numOfAds** (number) - Optional - The number of ads to preload.
- **requestNonPersonalizedAdsOnly** (boolean) - Optional - Whether to only request non-personalized ads.
- **expirationPeriod** (number) - Optional - The period after which ads expire (in milliseconds).
- **mediationEnabled** (boolean) - Optional - Whether mediation is enabled.
- **videoOptions** (VideoOptions) - Optional - Configuration for video ads.
- **mediationOptions** (MediationOptions) - Optional - Configuration for mediation settings.
- **targetingOptions** (TargetingOptions) - Optional - Configuration for ad targeting.
- **adChoicesPlacement** (string) - Optional - Placement of the ad choices icon (`"topLeft","topRight","bottomLeft","bottomRight"`).
- **mediaAspectRatio** (string) - Optional - The aspect ratio of the media content (`"any","landscape","portrait","square","unknown"`).
### `unRegisterRepository`
Unregister a repository. All preloaded ads in this repository will be destroyed.
### `resetCache`
Reset all ad repositories. This will clear all preloaded ads from all registered repositories.
### `hasAd`
Check if there is an ad available in a repository. This function typically requires a repository identifier (e.g., name or adUnitId) as a parameter, though it's not explicitly listed in the provided text. Assuming a signature like `hasAd(repositoryName: string): boolean`.
```
--------------------------------
### Use Preloaded Ads with Repository
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/nativeadview/nativeadview.md
Demonstrates how to use a preloaded ad by specifying the 'repository' prop in the NativeAdView component. When an ad is shown, it's replaced by a newly preloaded one.
```jsx
const AdView = () => {
const nativeAdViewRef = useRef();
React.useEffect(() => {
nativeAdViewRef.current?.loadAd();
}, []);
return (
/* All other ad components */
);
};
```
--------------------------------
### Register Ad Repository - JavaScript
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/admanager/repository.md
Registers a repository to preload ads in the background. It accepts an object with various configuration options like ad unit ID, number of ads to preload, and targeting preferences. This function is crucial for ensuring ads are ready when needed, improving user experience.
```javascript
registerRepository({
name: 'myRepository',
adUnitId: 'ca-app-pub-...',
numOfAds: 5,
requestNonPersonalizedAdsOnly: false,
expirationPeriod: 1200,
mediationEnabled: true,
videoOptions: {},
mediationOptions: {},
targetingOptions: {},
adChoicesPlacement: 'topRight',
mediaAspectRatio: 'landscape'
});
```
--------------------------------
### Import NativeAdView
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/nativeadview/nativeadview.md
Demonstrates how to import the NativeAdView component as the default export from the 'react-native-admob-native-ads' library.
```jsx
import NativeAdView from "react-native-admob-native-ads";
```
--------------------------------
### Configure Ad Requests and Initialize SDK using JavaScript
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/admanager/requestconfig.md
This JavaScript code snippet demonstrates how to use the `setRequestConfiguration` function to configure AdMob Native Ads. It initializes the SDK with various parameters including test device IDs, max ad content rating, child-directed treatment, and tracking authorization. The `trackingAuthorized` flag is dynamically set based on user permission obtained via `react-native-tracking-transparency`. This configuration should typically be done when the root component of the app mounts.
```javascript
const config = {
testDeviceIds: ["YOUR_TEST_DEVICE_ID"],
maxAdContentRating: "MA",
tagForChildDirectedTreatment: false,
tagForUnderAgeConsent: false,
};
export default function App() {
const [loading, setLoading] = useState(true);
useEffect(() => {
const init = async () => {
const trackingStatus = await requestTrackingPermission();
let trackingAuthorized = false;
if (trackingStatus === "authorized" || trackingStatus === "unavailable") {
trackingAuthorized = true;
}
await AdManager.setRequestConfiguration({
...config,
trackingAuthorized,
});
setLoading(false);
};
init();
}, []);
return (/* Your App code */)
}
```
--------------------------------
### AdManager - Preloading Ads
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/nativeadview/nativeadview.md
The AdManager allows you to preload ads using repositories, which can significantly improve ad loading performance by ensuring ads are ready when needed.
```APIDOC
## AdManager - Preloading Ads
### Description
`AdManager` provides functionality to preload ads using repositories. This is useful for showing ads instantly without user waiting time, especially when navigating between screens. Once an ad is shown, it's removed from the repository and a new one is preloaded.
### Method: `registerRepository`
Registers a repository for preloading ads.
#### Parameters
- **`repositoryConfig`** (object) - Configuration object for the ad repository.
- **`name`** (string) - Required - A unique name for the repository.
- **`adUnitId`** (string) - Required - The AdMob Ad Unit ID for the ads to be preloaded.
- **`numOfAds`** (number) - Optional - The number of ads to preload in this repository. Defaults to 1.
- **`nonPersonalizedAdsOnly`** (boolean) - Optional - If true, only non-personalized ads will be preloaded. Defaults to false.
- **`videoOptions`** (object) - Optional - Options for video ads.
- **`mute`** (boolean) - Optional - Whether to mute videos by default. Defaults to false.
- **`expirationPeriod`** (number) - Optional - The duration in milliseconds after which preloaded ads expire. Defaults to 3600000 (1 hour).
- **`mediationEnabled`** (boolean) - Optional - Whether mediation is enabled for this repository. Defaults to false.
#### Returns
A promise that resolves with a boolean indicating success (`true`) or failure (`false`).
### Usage Example - Registering a Repository
```jsx
import AdManager from 'react-native-admob-native-ads';
const NATIVE_AD_ID = 'ca-app-pub-3940256099942544/2247696110'; // Replace with your actual test Ad Unit ID
AdManager.registerRepository({
name: 'imageAd',
adUnitId: NATIVE_AD_ID,
numOfAds: 3,
nonPersonalizedAdsOnly: false,
videoOptions: {
mute: false,
},
expirationPeriod: 3600000, // 1 hour in milliseconds
mediationEnabled: false,
})
.then(result => {
console.log('Repository registered successfully:', result);
})
.catch(error => {
console.error('Error registering repository:', error);
});
```
### Usage Example - Using a Preloaded Ad Repository in `NativeAdView`
```jsx
import React, { useRef, useEffect } from 'react';
import { View } from 'react-native';
import NativeAdView from 'react-native-admob-native-ads';
const PreloadedAdView = () => {
const nativeAdViewRef = useRef();
useEffect(() => {
// Load ad from the registered repository
nativeAdViewRef.current?.loadAd();
}, []);
return (
/* All other ad components */
);
};
export default PreloadedAdView;
```
### Considerations
- **Automatic Refresh**: Ads do not refresh automatically from version `0.4.0` onwards to conserve bandwidth. You must manually reload ads when necessary.
- **Preventing Rerendering**: To prevent `NativeAdView` from rerendering and requesting new ads unintentionally, consider wrapping your component with `React.memo()` or using `React.PureComponent`.
```
--------------------------------
### Load Ad Imperatively with useRef
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/nativeadview/nativeadview.md
Illustrates how to load an ad imperatively using the `useRef` hook. A ref is attached to NativeAdView to call the `loadAd()` method, typically within a `useEffect` hook.
```jsx
const AdView = () => {
const nativeAdViewRef = useRef();
React.useEffect(() => {
nativeAdViewRef.current?.loadAd();
}, []);
return (
/* All other ad components */
);
};
```
--------------------------------
### NativeAdView Component
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/nativeadview/nativeadview.md
The NativeAdView component wraps all Ad components and provides a context for loading ads. It can be used with either an adUnitID or a repository for preloaded ads.
```APIDOC
## NativeAdView Component
### Description
The `NativeAdView` component is the main wrapper for displaying native ads. It provides a React Context through which all ad components load an ad. You can either provide an `adUnitID` directly or specify a `repository` name to use preloaded ads.
### Props
- **`style`** (object) - Optional - Styles to apply to the `NativeAdView`.
- **`repository`** (string) - Required if `adUnitID` is not provided - The name of the repository to use for preloading ads.
- **`adUnitID`** (string) - Required if `repository` is not provided - The AdMob Ad Unit ID for Native Advanced Ads. **Note**: Do not use your AdMob IDs during development; use test IDs instead.
- **`enableTestMode`** (boolean) - Optional - If true, loads a placeholder ad when internet is unavailable. Set `adUnitID` to null when using this.
- **`adChoicesPlacement`** (string) - Optional - Placement of the AdChoices icon. Possible values are `topLeft`, `topRight` (default), `bottomLeft`, `bottomRight`.
### Usage Example
```jsx
import NativeAdView from 'react-native-admob-native-ads';
import { View } from 'react-native';
const MyAdComponent = () => {
return (
/* All other ad components like AdImage, AdHeadline, etc. */
);
};
export default MyAdComponent;
```
### Loading Ads Imperatively
To load ads imperatively, you need to provide a `ref` to the `NativeAdView` component and call the `loadAd()` method.
```jsx
import React, { useRef, useEffect } from 'react';
import { View } from 'react-native';
import NativeAdView from 'react-native-admob-native-ads';
const AdView = () => {
const nativeAdViewRef = useRef();
useEffect(() => {
nativeAdViewRef.current?.loadAd();
}, []);
return (
/* All other ad components */
);
};
export default AdView;
```
```
--------------------------------
### setRequestConfiguration
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/admanager/requestconfig.md
Configures Ad requests and initializes the Mobile Ads SDK. This function must be called before loading any ads. It returns the initialization status of each mediation adapter.
```APIDOC
## setRequestConfiguration
### Description
Configures Ad requests and initializes the Mobile Ads SDK. You need to call this function before you load any Ads. Generally, you call this function when the root component of your app is mounted.
`setRequestConfiguration` returns `Promise` which is each mediation adapter's initialization status.
### Method
```
AdManager.setRequestConfiguration(config: RequestConfiguration): Promise
```
### Parameters
#### Request Body
- **testDeviceIds** (Array) - Optional - A list of test device IDs.
- **maxAdContentRating** (Ad Content Ratings) - Optional - Specifies the maximum ad content rating.
- **tagForChildDirectedTreatment** (boolean) - Optional - A flag to indicate if the request is for child-directed treatment.
- **tagForUnderAgeConsent** (boolean) - Optional - A flag to indicate if the request is for under-age consent.
- **trackingAuthorized** (boolean) - Optional - A flag to indicate if tracking is authorized. Required for iOS 14+ for Facebook.
### Request Example
```javascript
const config = {
testDeviceIds: ["YOUR_TEST_DEVICE_ID"],
maxAdContentRating: "MA",
tagForChildDirectedTreatment: false,
tagForUnderAgeConsent: false,
};
// For iOS 14+ tracking transparency:
// const trackingStatus = await requestTrackingPermission();
// let trackingAuthorized = false;
// if (trackingStatus === "authorized" || trackingStatus === "unavailable") {
// trackingAuthorized = true;
// }
await AdManager.setRequestConfiguration({
...config,
// trackingAuthorized: trackingAuthorized
});
```
### Ad Content Ratings
- **G**: "General audiences." Content suitable for all audiences, including families and children.
- **MA**: "Mature audiences." Content suitable only for mature audiences; includes topics such as alcohol, gambling, sexual content, and weapons.
- **PG**: "Parental guidance." Content suitable for most audiences with parental guidance, including topics like non-realistic, cartoonish violence.
- **T**: "Teen." Content suitable for teen and older audiences, including topics such as general health, social networks, scary imagery, and fight sports.
- **UNSPECIFIED**: Set default value to ""
### MediationAdapterStatus
- **name** (string) - The name of the mediation adapter.
- **description** (string) - A description of the mediation adapter.
- **state** (AdapterState) - The initialization state of the adapter.
#### AdapterState
`enum AdapterState { NOT_READY, READY }`
```
--------------------------------
### Display AdBadge Component (JSX)
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/components/adbadge.md
Demonstrates how to import and use the AdBadge component in a React Native application. It shows basic styling for the badge and its text, emphasizing its role in ad identification.
```jsx
import { AdBadge } from "react-native-admob-native-ads";
;
```
--------------------------------
### Handle Ad Interaction Events - React Native
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/nativeadview/events.md
These event props capture user interactions with the native ad. `onAdOpened`, `onAdClosed`, `onAdLeftApplication`, and `onAdClicked` allow you to track user engagement. `onAdImpression` is called when an ad impression is recorded.
```javascript
import React from 'react';
import { View } from 'react-native';
import { NativeAdView } from 'react-native-admob-native-ads';
const AdComponent = () => {
const handleAdOpened = () => console.log('Ad opened');
const handleAdClosed = () => console.log('Ad closed');
const handleAdLeftApplication = () => console.log('Ad left application');
const handleAdClicked = () => console.log('Ad clicked');
const handleAdImpression = () => console.log('Ad impression recorded');
return (
{/* Ad UI elements */}
);
};
export default AdComponent;
```
--------------------------------
### Render NativeMediaView Component in React Native
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/components/media.md
This snippet demonstrates how to import and use the NativeMediaView component from the 'react-native-admob-native-ads' library. It shows basic styling for width and height, suitable for displaying video or image ad assets. No specific external dependencies are required beyond the library itself.
```jsx
import { NativeMediaView } from "react-native-admob-native-ads";
;
```
--------------------------------
### Handle Native Ad Loaded Event - React Native
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/nativeadview/events.md
The `onNativeAdLoaded` event prop is triggered when a native ad is successfully loaded. It provides a data object containing all ad-related information, such as headline, description, images, and call-to-action. This data can be used to populate ad views, although often the library handles automatic rendering.
```javascript
import React from 'react';
import { View, Text } from 'react-native';
import { NativeAdView } from 'react-native-admob-native-ads';
const AdComponent = () => {
const handleAdLoaded = (event) => {
console.log('Native ad loaded:', event);
// Access ad data like event.headline, event.images, etc.
};
return (
{/* Ad UI elements here */}
);
};
export default AdComponent;
```
--------------------------------
### Ad Media Aspect Ratio Configuration
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/nativeadview/nativeadview.md
Configure the preferred aspect ratio for native ads. While you can specify a preference, AdMob is not guaranteed to return an ad matching the requested aspect ratio.
```APIDOC
## `mediaAspectRatio`
You can specify to Admob what kind of ad you want to receive however it is not guaranteed that you will receive the same ad you requested.
### Values:
- **unknown**: Show whatever ad is available.
- **any**: Any ads are preferred (default).
- **landscape**: Landscape ads are preferred.
- **portrait**: Portrait ads are preferred.
- **square**: Square ads are preferred.
### Default Value:
`any`
```
--------------------------------
### Render Advertiser Name with AdvertiserView (JSX)
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/components/advertiser.md
This snippet demonstrates how to use the AdvertiserView component to display the advertiser's name. It imports the component and applies basic styling. The AdvertiserView inherits all props from the standard Text component, offering flexibility in presentation.
```jsx
import { AdvertiserView } from "react-native-admob-native-ads";
;
```
--------------------------------
### Check for Available Ad - JavaScript
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/admanager/repository.md
Checks if there is a preloaded ad available in a specified repository. This function returns a boolean value indicating the presence of an ad, allowing you to conditionally display ads.
```javascript
const hasAd = hasAd('myRepository');
console.log(`Ad available: ${hasAd}`);
```
--------------------------------
### Handle Ad Failed to Load Event - React Native
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/nativeadview/events.md
The `onAdFailedToLoad` event prop is called when an ad fails to load. It provides a reason for the failure, which is useful for debugging and logging purposes. Implement this handler to gracefully manage ad loading errors.
```javascript
import React from 'react';
import { View } from 'react-native';
import { NativeAdView } from 'react-native-admob-native-ads';
const AdComponent = () => {
const handleAdFailedToLoad = (event) => {
console.error('Ad failed to load:', event.error);
// Handle the error, e.g., show a placeholder or retry
};
return (
{/* Ad UI elements */}
);
};
export default AdComponent;
```
--------------------------------
### Requesting Non-Personalized Ads
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/nativeadview/nativeadview.md
Configure whether to request non-personalized ads only. This is crucial for complying with the Google EU User Consent Policy and GDPR, especially for users in the EEA.
```APIDOC
## `requestNonPersonalizedAdsOnly`
Under the Google EU User Consent Policy, you must make certain disclosures to your users in the European Economic Area (EEA) and obtain their consent to use cookies or other local storage, where legally required, and to use personal data (such as AdID) to serve ads. This policy reflects the requirements of the EU ePrivacy Directive and the General Data Protection Regulation (GDPR).
You can use a library such as `react-native-ad-consent` to obtain the consent or if you are using `rn-firebase`, you can obtain the consent from there and then pass the consent to this library. If the user has selected non-personalized ads, then pass `true` and non-personalized ads will be shown to the user.
### Parameters:
- **`requestNonPersonalizedAdsOnly`** (boolean) - Optional - If `true`, only non-personalized ads will be served. Defaults to `false`.
```
--------------------------------
### Render CallToAction Button with React Native
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/components/calltoaction.md
This snippet demonstrates how to import and use the CallToActionView component from 'react-native-admob-native-ads'. It shows basic styling for the outer view and inner text, allowing for customization of appearance.
```jsx
import { CallToActionView } from "react-native-admob-native-ads";
;
```
--------------------------------
### Unregister Ad Repository - JavaScript
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/admanager/repository.md
Unregisters a specific ad repository, destroying all preloaded ads associated with it. This is useful for cleaning up resources when a repository is no longer needed, preventing memory leaks.
```javascript
unRegisterRepository('myRepository');
```
--------------------------------
### Reset Ad Cache - JavaScript
Source: https://github.com/ammarahm-ed/react-native-admob-native-ads/blob/master/docs/docs/admanager/repository.md
Resets the cache for all registered ad repositories. This action invalidates all currently preloaded ads across the application, forcing a fresh preload cycle.
```javascript
resetCache();
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.