I would like to create a SEO friendly URL pattern on clientside. The ID of an article is fetched from the server by searching for the ID.
I would like to integrate the title of the article in the URL on the clientside, to have more SEO friendly URLs.
https://www.myurl.com/this-is-my-articles-name-854353
That means, only the last part of the URL must be considered to fetch the data correctly from the server. All hyphens before must be ignored.
How can I achieve this using React Router?
The following example with a user’s profile.
So bascially the implementation is:
And I would like to attach a SEO-friendly string. That means, the router only must consider the "small_id", not the string before
https://myurl.com/vendor/firstname-lastname-location-other-stuff-c0la
App.js
<Routes>
<Route exact path="/" element={<Home />} />
<Route exact path="/chats" element={<Chats />} />
<Route exact path="/profil" element={<Profile />} />
<Route path="/vendor/:small_id" element={<ViewProfile />} />
<Route exact path="/dashboard" element={<Dashboard />} />
<Route exact path="/verwaltung" element={<File />} />
</Routes>
SearchResults.js (This links to the profile)
<div className="section-box profile" key={key} onClick={() => navigate('/vendor/' + user.small_id)}>
ViewProfile.js (The profile of the found users)
const { small_id } = useParams(); // Must match the pattern used in the router
React.useEffect(() => {
axios.get('/api/profiles/get/' + small_id)
.then(res => {
if (res.status === 200) {
setProfile(res.data);
}
})
.catch(err => {
//toast.error("Der Benutzer wurde nicht gefunden", { theme: 'colored' });
})
}, []);
2
Answers
I did some research and discovered that React Router V6 does not accept optional parameters anymore. So I came up with the following solution:
That means the path can look like: https://mywebsite.com/vendor/+843242
And ":seo" is basically optional. You do not need this, if you implement the server routing like this:
So everything before :+small_id can be fully customized for SEO purposes. You can route what you want clientside.
So I would change your route to the following:
I would then re build your link to include those:
The below should still work:
** Please note I have not tested this!