I am building a markdown blog using React. I want to add the next and previous post buttons in the footer of the post page. Here is the code-
App.tsx–
<Route path='/blog'>
<Route index element={<BlogPage />} />
<Route path=":ID" element={<Postpage/>}/>
</Route>
city.json file-
[
{
"header": "Michigan ",
"id": "MI",
"PlaceList": [
{
"city": "Detroit",
"url": "/url-for-detroit-city"
},
{
"city": "Lansing ",
"url": "/url-for-lansing-city"
}
]
},
{ "header": "Iowa ",
"id": "IA",
"PlaceList": [
{
"city": "Ames",
"url": "/url-for-ames-city"
},
{
"city": "Davenport ",
"url": "/url-for-davenport-city"
}
]
}
]
Postpage.tsx–
import { useParams } from "react-router-dom"
import city from './city.json'
import { useEffect, useState } from "react"
import Markdown from "react-markdown"
const Postpage = () => {
//Get ID from URL
const { ID } = useParams()
// Create a flat map
const allPosts = city.flatMap(({ header, id, PlaceList }) =>
PlaceList.map((topics) => ({
sectionName: header,
sectionId: id,
...topics,
})),
);
// Filter by url
const filterPosts = allPosts.filter(({ url }) => url.trim() === id);
const [page, setPage] = useState(1)
const [posts, setPosts] = useState('')
//Get the post body
useEffect(() => {
import(`./markdown/${id}.md`)
// the markdown files are named accordingly so that they match with ${id}
.then(res => {
fetch(res.default)
.then(res => res.text())
.then(res => setPosts(res))
.catch(err => console.log(err));
})
.catch(err => console.log(err));
})
//get the next & previous post
const nextPage = () => setPage(prev => prev +1)
const prevPage = () => setPage(prev => prev - 1)
return (
<article>
<Markdown>
{posts}
</Markdown>
<button className="float-left text-teal-600" onClick={prevPage} disabled={page === 1}>Prev Page</button>
<button className="float-right text-teal-600" onClick={nextPage} disabled={!allPosts.length}>Next Page</button>
</article>
)
}
export default Postpage
The article shows up properly, here is the example page-
However, the previous and next buttons do not work. I would like to get the URL of the next/previous article from the JSON file and get the post. And if it hits the end (aka no previous or next article available) I would like them to disappear or grayed out