'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:_)
Solution 1:[1]
a well put question. I asked myself the same. Here is how I did it.
- 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>
- 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |