We recommend using routing libraries that are agnostic to your codebase structure, such as React Router.
Set react-router-dom as a peer dependency in your env's env.jsonc
file, to avoid possible conflicts between different versions of this library.
/* @filename: env.jsonc */ { "policy": { "peers": [ { "name": "react-router-dom", /* version to be installed and used by the env, for component previews */ "version": "6.8.1", /* the peer dependency version range that the components are compatible with */ "supportedRange": "^6.8.1" } ] } }
Run the following to install the new peer dependency:
Add react router to your component or app component. For example:
import React from 'react'; import { Routes, Route } from 'react-router-dom'; import { Homepage } from '@teambit/community.ui.pages.homepage'; export function BitDevApp() { return ( <div> <Routes> <Route path="/" element={<Homepage />} /> </Routes> </div> ); }
You can also nest components that implement their own routing. For example, the following Blog component has its own routing. The blog's routing is nested under the root routing of this app component:
import React from 'react'; import { Routes, Route } from 'react-router-dom'; import { CommunityBlog } from '@teambit/blog.community.blog'; export function BitDevApp() { return ( <div> <Routes> <Route path="/blog/*" element={<CommunityBlog />} /> </Routes> </div> ); }
Implement routing only in components that have little or no dependents, like apps and sections, to keep your components compatible with other routing systems.
Components containing non-native links fail when consumed in apps that do not use the proper routing system. For example, a component containing React Router Link will fail when used in a NextJS application, or even when used in a legacy version of React Router.
Bit provides a Link component that is compatible with all routing systems.
The Link component returns a link implementation that fits its hosting routing system. If no system is defined, Link defaults to a standard anchor tag (<a href=""></a>
).
For example:
import { BrowserRouter, Route, Routes } from 'react-router-dom'; import { NavigationProvider, Link } from '@teambit/base-react.navigation.link'; import { reactRouterAdapter } from '@teambit/ui-foundation.ui.navigation.react-router-adapter'; import { Homepage } from '@teambit/community.ui.pages.homepage'; export function App() { return ( <BrowserRouter> <NavigationProvider implementation={reactRouterAdapter}> <Link href="/">Home</Link> <Routes> <Route path="/" element={<Homepage />} /> </Routes> </NavigationProvider> </BrowserRouter> ); }
To learn more see the Link component page.
NextJS comes with built-in routing system you can use. Learn more on the NextJS docs.