I'm attempting to use an onClick listener for dynamically created blog posts to direct the user to the blog post page and render the posts contents. I originally wanted to use a custom hook but have tried to centralize things so you can see what I'm doing.
import { useState } from 'react';
import { Link } from 'react-router-dom';
import Card from '../../shared/components/UIElements/Card';
import { useBlog } from '../../shared/hooks/blog-hook';
const BlogContainer = () => {
const { blogs } = useBlog()
const [blogID, setBlogID] = useState(null);
const getBlogID = () => {
setBlogID(blogID);
};
const displayBlogs = blogs.map((blog) => {
return (
<Link
onClick={getBlogID}
to={`/${blog.key}`}
key={blog.key}
>
<Card className="mapped">
<h2>{blog.title}</h2>
<h4>{blog.description}</h4>
</Card>
</Link>
);
});
return <div className="blog-container">{displayBlogs}</div>;
};
export default BlogContainer;
import { useBlog } from '../../shared/hooks/blog-hook';
const BlogPost = () => {
const { blogID } = useBlog();
return (
<>
<h1>{`${blogs[blogID]}`}</h1>
</>
);
};
export default BlogPost;
What should happen is when a blog is clicked, it sets blog.key to blogID, which then is used to identify the specific blog on the blog page to be displayed. The problem is when I click a blog link it doesn't setBlogID at all, let alone to the blog clicked on. I've tried it with and without "this." in setBlogID, and both using/not using an anonymous function, but I get the same results. The console is logging blogID as "null".
Edits: removed () => from onClick, removed this. from setBlogID, added blog post page for reference.