I am creating a blog on React using the firebase database, but I don’t understand how to make a post page where you can see the article in more detail, as well as where there will be photos and id ... Can you suggest how best to do it, maybe there will be examples with this topic, in advance thank)
CodePudding user response:
you pass the firebase document id into the url like this
App.js
<Route path="blog">
<Route path=":blogid" element={<BlogPageComponent />} />
</Route>
then you get the id in the BlogPageComponent from the url like this
BlogPageComponent.js
import { useParams } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { doc, getDoc} from "firebase/firestore";
import { db } from "../firebaseConfig"
export const BlogPageCoponent = () => {
const { blogid } = useParams()
const [blog, setBlog] = useState(null)
useEffect(() => {
const getBlog = async () => {
const blogRef= doc(db, "blogs", blogid) //database, "blogs" collection, document with id
const data = await getDoc(blogRef);
if (data.exists()) {
setBlog(data.data())
}
}
getBlog()
}, [])
return (
<div>
<h2>{blog.title}</h2>
</div>
)
}
assuming you have a "title: My blog" in firebase doc
and in another page like HomePage you have a link to go to the blog like this
import { NavLink } from 'react-router-dom'
import { collection, getDocs } from "firebase/firestore";
export const Homepage = () => {
const [blogs, setBlogs] useState([])
useEffect(() => {
const getBlogs = async (uid: string) => {
const blogsRef = collection(db, "blogs")
const data = await getDocs(blogsRef);
list = []
data.forEach((doc) => {
list.push({...doc.data(), id: doc.id})
})
setBlogs(list)
}
getBlogs()
}, [])
return (
<div>
{blogs.map((blog, i) => (
<NavLink key={i} to={"/blog/" blog.id}>{blog.name}</NavLink>
)}
</div>
)
}
package.json
"firebase": "^9.6.10",
"react-router-dom": "^6.0.2",
CodePudding user response:
I made this repository a while ago. you can try it here
Altho it doesn't contain the option to upload pictures but it can give you a start. If you need any assistance, let me know.