For a beginner software engineer who recently began religiously studying and using React, I was exposed to many different frontend and backend libraries which helped me in my app development journey. Creating a dynamic PWA served from a database with a backend is a lot more than just creating static blogs/websites, and in this article, I will focus on the difference between path
and url
from the useRouteMatch
hook found in the react-router-dom
library.
Giving users the ability to dynamically make CRUD requests means that the URLs of the served content are matched with the content, therefore, knowing the distinction between path
and url
is crucial to frontend routing with React. These URLs usually have parameters defined in the route, and allow users to render uniquely created content.
import React from 'react'
import { BrowserRouter, Switch, Route, Link, useParams, useRouteMatch } from 'react-router-dom'
export default function App() {
return (
<BrowserRouter>
<div>
<h1>Title</h1>
<ul>
<li><Link to="/topic1">Topic1</Link></li>
<li><Link to="/topic2">Topic2</Link></li>
<li><Link to="/topic3">Topic3</Link></li>
<li><Link to="/topic4">Topic4</Link></li>
</ul>
<Switch>
<Route path="/:topicId" component={Topic}/>
</Switch>
</div>
</BrowserRouter>
)
}
function Topic() {
let { topicId } = useParams()
let { path, url } = useRouteMatch()
return (<>
<h1>{topicId}</h1>
<h2>{path}</h2>
<h2>{url}</h2>
</>)
}
With the above code snippet, a parameter :topicId
is used in the Routes to render dynamic Topics. From the Topic
component, the topicId
, path
and url
are rendered on the site, and we can see that path
simply returns the parametrised /:topicId
, while url
returns /topic1
.
According to Official React Router DOM Documentation, path
is defined as “The path pattern used to match. Useful for building nested <Route>
s”, while url
is defined as “The matched portion of the URL. Useful for building nested <Link>
s”.
This makes sense, as when writing links, we have to use url
because it allows us to navigate to the actual path we want. Additionally, when writing routes, we are simply giving the browser router a pattern/parameter which it will attempt to match, and subsequently render out content for. When the content being served in a SPA has the same format generally (think maybe forum posts), the browser router can simply match the parameters accordingly, fetch the required content from a server, and display it.
Don’t forget to install the react-router-dom
dependency before using it!
> npm install --save react-router-dom
OR (usually if one fails, the other one works)
> yarn add react-router-dom