I wanted to make a single blog page of a blog website to read but it's not working
I want someone help me to solve this error.
App.js
import Demo from "./components/Pages/Demo/Demo";
import DemoPost from "./components/Pages/Demo/Post";
function App() {
return (
<div>
<Routes>
<Route path='/posts' exact element={<Demo />} />
<Route path='/demo/:pid' element={<DemoPost />} />
</Routes>
</div>
);
}
export default App;
Posts.js
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
function Demo() {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(json => setPosts(json))
}, []);
return (
<div className="posts">
<div className="grid">
{posts.map(post => (
<div key={post.id}>
<Link to={`/posts/${post.id}`}>
<h2>{post.title}</h2>
<p>{post.body}</p>
</Link>
</div>
))}
</div>
</div>
)
}
export default Demo
Post.js
import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
function Post({ match }) {
const [post, setPost] = useState([]);
useEffect(() => {
fetch(`https://jsonplaceholder.typicode.com/posts${match.params.pid}`)
.then(response => response.json())
.then(json => setPost(json))
console.log(match, 'why not show match');
}, []);
return (
<div className="posts">
<div className="post-container">
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
</div>
)
}
export default Post
CodePudding user response:
For the link <Link to={`/posts/${post.id}`}>
you need to render a route path that matches, e.g. path="/posts/:pid"
.
<Routes>
<Route path='/posts' exact element={<Demo />} />
<Route path='/posts/:pid' element={<DemoPost />} />
</Routes>
react-router-dom@6
Route
components also no longer pass route props to the routed component. The element
component should use the useParams
hook to access the route path params.
import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
function Post() {
const { pid } = useParams();
const [post, setPost] = useState();
useEffect(() => {
fetch(`https://jsonplaceholder.typicode.com/posts/${pid}`)
.then(response => response.json())
.then(json => setPost(json));
}, [pid]); // <-- pid is effect dependency
if (!post) {
return null; // <-- or loading indicator/spinner/etc
}
return (
<div className="posts">
<div className="post-container">
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
</div>
);
}