'How to display blog post detail page in react?

How can I display the blog post page when a specific slug appears in URL like ".blog/post-slug". I am trying to save post article HTML code in an array in PostData.jsx file. How to fetch data from it and display it to the user.

PostData.jsx File

const PostData = [
    {
        id: 1,
        slug: "post-slug",
        content: `Here HTML Content`,
    }
]

Post.jsx File

const Post = () => {
    }

export default Post;

Or is there any other optimized method to display it?



Solution 1:[1]

You can use react-router to achieve that:

<Route path="/blog/:slug">
  <Post />
</Route>

You can use useParams hook on the post page to get slug:

const Post = () => {
  const { slug } = useParams();
  const currentPost = postData.find((post) => post.slug === slug);

  return (
    // render
  );
}

More info about react-router and useParams hook:
https://v5.reactrouter.com/web/api/Hooks/useparams

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yurii Brusentsov