Creating a Post Show Page in React

Aug 22, 2024

Lecture Notes: Creating a Post Show Page in React

Overview

  • Continuation from last session.
  • Main focus: Adding functionality for a post show page in a React application.

Creating the Post Show Page

  • Start with the post index page.
  • Create a new branch for the post show page.

Setting Up React Router

  • React is a single-page application; requires routing to navigate.
  • Use react-router-dom for routing.
  • Install dependency: npm i react-router-dom.
  • Import BrowserRouter as Router in app.jsx.

Navbar Setup

  • Create a navbar component in navbar.jsx.
  • Import React and Link from react-router-dom.
  • Function NavBar: Links to a post list and a new post form.
  • Ensure to export default NavBar at the end.

App Routes

  • Replace PostList with AppRoutes component.
  • Create and import AppRoutes from components.
  • In appRoutes.jsx, import Routes and Route from react-router-dom.
  • Define routes:
    • / for PostList.
    • /new for a new post form.
    • /posts/:id for PostDetails.
  • Export default AppRoutes.

Implementing Post Details

  • Create postDetails.jsx in the posts directory.
  • Import necessary hooks and components:
    • useState, useParams from react-router-dom.
  • Function PostDetails: Fetches and displays individual post details.
  • Use useEffect to fetch post details on component mount and when ID changes.

Fetch Post Logic

  • Function fetchCurrentPost: Uses fetch to get post data by ID.
  • Check response and handle JSON data.
  • Error handling with console.log in a catch block.

Rendering Post Details

  • Render post title and body.
  • Simple error checking for null values.
  • Use loading state to handle asynchronous fetch delays.

Final Steps

  • Commit changes with a message (e.g., "add routing and post show page").
  • Push changes and create a pull request.
  • Review and merge pull request.

Conclusion

  • Next session: Editing, deleting, or creating posts.
  • Overview of changes and process on GitHub.