Divad
Divad

Reputation: 283

How to add title of a article into URL in Reactjs?

I am trying to know if it is possible or not to add the title of an article into the URL after redirecting to a specific article?

An example:

https://www.analyticsinsight.net/top-50-programming-languages-learn-coding/

so I am using reactjs with nodejs and MySQL.

I have a table with their columns, post_Text, post_Title, etc.

I only need to add the title of the article to the URL after User clicks on the title of a specific article.

i have a router as follows.

   <Route path="/post/:id" exact>
          <Post />
  </Route>

and in the post.js file, I have a simple get method.

axios.get(`${server}/posts/byId/${id}`).then((res) => {
  setPosts(res.data);
});

i would appreciate your help:_)

Upvotes: 3

Views: 1280

Answers (1)

Akin Fagbohun
Akin Fagbohun

Reputation: 56

a well put question. I asked myself the same. Here is how I did it.

  1. I set up the route, much like you have but with a second route that had another level of depth and another param on the end.

    <Route path="/post/:id" exact><Post /></Route>     
    <Route path="/post/:id/:post_title" exact><Post /></Route>

  1. On the click handler that navigates to the post, I did this. The values passed here. The regex simply identifies white spaces so that they can be replaced with a string.replace method.

    const handleReadPost = (post_id, post_title) => {
    const urlRegex = /\s/g;
    const url_title = post_title.toLowerCase().replace(urlRegex, '-');

    navigate(`/posts/${post_id}/${url_title}`);
    };

In my case, it then just worked. I didn't need to make any adjustments to my Axios GET or logic in the Post component.

Upvotes: 4

Related Questions