parametersreact-hooksreact-routeruse-effectjsonplaceholder

post detail doesn't show by click in react hooks


when I click on each post item the details doesn't show on the browser(post.js component for showing detail of each post item). only thing that shows on the browser is white page! . these are my components:

thank you for your help.

this is my App.js component:

import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./components/Home";
import About from "./components/About";
import Contact from "./components/Contact";
import Post from "./components/Post";

const App = () => {
  return (
    <BrowserRouter>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home/>}></Route>
        <Route path="about" element={<About/> }></Route>
        <Route path="contact" element={<Contact/>}></Route>
        <Route path="/posts/:id" element={<Post/>}></Route>
      </Routes>
    </BrowserRouter>
  );
};

export default App;

and Home.js component:

import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";

const Home = () => {
  const [posts, setPosts] = useState([]);
  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((response) => response.json())
      .then((data) => {
        setPosts(data.slice(0, 10));
      });
  }, []);
  return (
    <div className="container">
      <h4 className="center">Home</h4>
      {posts.map((post) => (
        <div className="post card" key={post.id}>
          <div className="card-content">
            <Link to={`/posts/${post.id}`}>
              <span className="card-title">{post.title}</span>
            </Link>
            <p>{post.body}</p>
          </div>
        </div>
      ))}
    </div>
  );
};

export default Home;

AndPost.js component for showing detail of each post item by click:

import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";

const Post = () => {
  const { id } = useParams();
  const [post, setPost ]= useState(null);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(
        `https://jsonplaceholder.typicode.com/posts/${id}`
      );
      const newData = await response.json();
      setPost(newData);
    };
    fetchData();
  }, [id]);

  return (
    <div>
      <p>{post.title}</p>
       <p>{post.body}</p>
    </div>
  );
};

export default Post;

Solution

  • From what I can tell, and reproduce, your code throws an error when Post tried to render post.title on the initial render before the post state is populated. The initial post state value is null and you can't access properties of a null or undefined value.

    You should conditionally render the post state.

    Example:

    return post ? (
      <div>
        <p>{post.title}</p>
        <p>{post.body}</p>
      </div>
    ) : null; // or some loading indicator, etc...
    

    Edit post-detail-doesnt-show-by-click-in-react-hooks