1

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;
2
  • Why not do "/" + title.replaceAll(" ", "-") Commented Aug 20, 2022 at 22:09
  • 1
    That's simple and works like a charm. Make it an official answer so I can accept it. Thank you! Commented Aug 20, 2022 at 22:13

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

1

Use slugify npm package to make your title a slug: https://www.npmjs.com/package/slugify

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.