3

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:_)

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Well explained.

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.