react-router
?The react-router
is an npm package for React that enables client-side routing. Traditionally, a browser requests the web server for a document. For example, when the user enters a link in the address bar or clicks on a hyperlink in the current document.
The slides below show the process for a web request using the address bar:
The slides below show the process for a web request using a hyperlink:
The client-side routing implemented by the react-router
package allows links to render a new document without sending a request to the web server. Moreover, it also manipulates the browser's history stack, so no request to the web server is sent when the user navigates backward or forward via the browser's built-in buttons.
So then, what are react-router-dom
and react-router-native
?
react-router-dom
packageFrom version 4 onwards, the react-router
only includes the core components required for client-side routing. However, the DOM-specific components (including the core components) are present in the react-router-dom
package, such as the <Link>
and <BrowserRouter>
tags. The following code snippet provides an example:
The application above renders three different pages depending on the URL specified. We enclose our complete application code within the <BrowserRouter>
tag that enables the <Routes>
, <Route>
and <Link>
tags to function properly.
Lines 16–20: The <Routes>
tag contains three <Route>
tags, each specifying the route and the corresponding element to be displayed.
Lines 21–25: The <Link>
tags act as a navigation bar, enabling users to shift between pages.
Did you notice the import comment on line 4? This was done purposefully to highlight that the <Routes>
and <Route>
tags are present in the react-router
package but the <BrowserRouter>
and <Link>
tags are not.
react-router-native
packageThe react-router-native
package, however, provides components specific to React Native applications, such as the <NativeRouter>
tag instead of the <BrowserRouter>
tag. Moreover, the <Link>
tag in this package is tailored to Native applications as opposed to the react-router-dom
's <Link>
tag, which is tailored to web applications.
Another key difference between the two packages is that the DOM package contains new routers that support data APIs introduced in version 6.4. However, currently, version 6 doesn't support such routers and data APIs for the native package.
Free Resources