I want to create a feed where a Google Ad is shown after every 10 posts just like Instagram. I am using Firebase as my database and tailwind-CSS for the styling. How would I use Google Ads to implement this feature?
Here is my code for displaying a Feed
Feed.js
import {React, useState, useEffect} from "react";
import Navbar from "./Navbar";
import Post from "./Post";
import { onSnapshot, collection, query, orderBy } from "@firebase/firestore";
import { db } from "../firebase";
function Feed() {
const [posts, setPosts] = useState([]);
useEffect(
() =>
onSnapshot(
query(collection(db, "posts"), orderBy("timestamp", "desc")),
(snapshot) => {
setPosts(snapshot.docs);
}
),
[db]
);
return (
<div>
<Navbar />
<div className="pb-72">
{posts.map((post) => (
<Post key={post.id} id={post.id} post={post.data()} />
))}
</div>
</div>
);
}
export default Feed;
CodePudding user response:
The javascript map
function has a second parameter - index
- that tells you the index of the item in the array it is iterating. So you would want to make two key changes:
return (
<div>
<Navbar />
<div className="pb-72">
{posts.map((post, idx) => {
// If true, you're on the tenth post
const isTenthPost = (idx 1) % 10 === 0
// Note the addition of the React fragment brackets - your map call
// has to return a single React component, so we add this to handle
// the case where we want to return both the post and the Google ad.
return (
<>
<Post key={post.id} id={post.id} post={post.data()} />
{ isTenthPost && <GoogleAdComponent /> }
</>
)
})}
</div>
</div>
);
I'm not suggesting you copy and paste this exactly, but it should help you understand how to determine if you're on the nth post and how to conditionally display another component.