I am trying to get the title to also be the hyperlink. However, I need to add dashes for the hyperlinks to work on articles with titles that are longer than one word. What would be the best method to achieve this?
Current Code:
https://example.com/example 01
What I'm Looking For:
https://example.com/example-01
Example Code Below:
#Post.tsx
import "./Posts.css";
import Post from "../Post/Post";
const Posts = () => {
const blogPosts = [
{
title: "Example 01",
body: "Example Description",
author: "John Doe",
imgUrl: "https://image.jpg },
{
title: "Example 02",
body: "Example Description",
author: "Jane Doe",
imgUrl: "https://image.jpg" }
];
return (
<div className="posts-container">
{blogPosts.map((post, index) => (
<Post key={index} index={index} post={post} />
))}
</div>
);
};
export default Posts;
#Post.tsx
import "./Post.css";
const Post = ({ post: { title, body,
imgUrl, author }, index }) => {
return (
<div className="post-container">
<h1 className="heading">{title}</h1>
<img className="image" src={imgUrl} alt="post" />
<div className="info">
<h4>Written by: {author}</h4>
</div>
<p>{body}</p>
<p><a href={"/" title}>Read More</a></p>
</div>
);
};
export default Post;
CodePudding user response:
Use slugify
npm package to make your title a slug:
https://www.npmjs.com/package/slugify
CodePudding user response:
In your Post
component, you can just replace all spaces in the title with dashes for the link target:
import "./Post.css";
const Post = ({ post: { title, body, imgUrl, author }, index }) => {
return (
<div className="post-container">
<h1 className="heading">{title}</h1>
<img className="image" src={imgUrl} alt="post" />
<div className="info">
<h4>Written by: {author}</h4>
</div>
<p>{body}</p>
<p><a href={"/" title.replaceAll(" ", "-")}>Read More</a></p>
</div>
);
};
export default Post;