
Security News
MCP Community Begins Work on Official MCP Metaregistry
The MCP community is launching an official registry to standardize AI tool discovery and let agents dynamically find and install MCP servers.
react-router-dom
Advanced tools
The react-router-dom package is a popular library for handling routing in React web applications. It allows developers to implement dynamic routing in a web app, which is not possible with static routing. With react-router-dom, you can define routes, navigate between them, handle parameters and query strings, and manage the history stack, among other things.
Basic Routing
This code demonstrates how to set up basic routing in a React application using react-router-dom. It uses the BrowserRouter, Route, and Switch components to define routes for different components in the app.
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
<Router>
<Switch>
<Route exact path='/' component={Home} />
<Route path='/about' component={About} />
<Route path='/contact' component={Contact} />
</Switch>
</Router>
);
}
Link Navigation
This code snippet shows how to use the Link component to create navigation links that allow users to click through different routes without causing a page reload.
import { Link } from 'react-router-dom';
function Navbar() {
return (
<nav>
<Link to='/'>Home</Link>
<Link to='/about'>About</Link>
<Link to='/contact'>Contact</Link>
</nav>
);
}
Route Parameters
This example demonstrates how to handle dynamic routes using route parameters. The useParams hook is used to access the parameters of the current route.
import { Route, useParams } from 'react-router-dom';
function User() {
let { userId } = useParams();
return <h2>User ID: {userId}</h2>;
}
function Users() {
return (
<Route path='/users/:userId' component={User} />
);
}
Programmatic Navigation
This code shows how to navigate programmatically using the useHistory hook. It allows you to push a new entry onto the history stack, mimicking the behavior of a navigation action.
import { useHistory } from 'react-router-dom';
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push('/home');
}
return (
<button type='button' onClick={handleClick}>
Go home
</button>
);
}
Reach Router is another routing library for React with a more straightforward, accessible approach compared to react-router-dom. It automatically manages focus for accessibility, and routing is more component-based. However, as of my knowledge cutoff in 2023, Reach Router has been officially merged with React Router, and the team recommends using React Router for new projects.
Wouter is a minimalist routing library for React and Preact that does not rely on the context API. It offers a simpler API and smaller bundle size compared to react-router-dom, making it a good choice for smaller projects or when you want to keep your project lightweight.
Navi is a JavaScript library for declaratively mapping URLs to asynchronous content. It's designed to work with React and allows for lazy-loading routes, which can help improve performance in large applications. Navi provides a different approach to routing by focusing on content-first routing, which can be beneficial for certain types of applications.
This package simply re-exports everything from react-router
to smooth the upgrade path for v6 applications. Once upgraded you can change all of your imports and remove it from your dependencies:
-import { Routes } from "react-router-dom"
+import { Routes } from "react-router"
v7.6.0
Date: 2025-05-08
routeDiscovery
Config OptionWe've added a new config option in 7.6.0
which grants you more control over the Lazy Route Discovery feature. You can now configure the /__manifest
path if you're running multiple RR applications on the same server, or you can also disable the feature entirely if your application is small enough and the feature isn't necessary.
// react-router.config.ts
export default {
// You can modify the manifest path used:
routeDiscovery: { mode: "lazy", manifestPath: "/custom-manifest" }
// Or you can disable this feature entirely and include all routes in the
// manifest on initial document load:
routeDiscovery: { mode: "initial" }
// If you don't specify anything, the default config is as follows, which enables
// Lazy Route Discovery and makes manifest requests to the `/__manifest` path:
// routeDiscovery: { mode: "lazy", manifestPath: "/__manifest" }
} satisfies Config;
Some future flags alter the way types should work in React Router. Previously, you had to remember to manually opt-in to the new types. For example, for future.unstable_middleware
:
// react-router.config.ts
// Step 1: Enable middleware
export default {
future: {
unstable_middleware: true,
},
};
// Step 2: Enable middleware types
declare module "react-router" {
interface Future {
unstable_middleware: true; // š Enable middleware types
}
}
It was up to you to keep the runtime future flags synced with the types for those flags. This was confusing and error-prone.
Now, React Router will automatically enable types for future flags. That means you only need to specify the runtime future flag:
// react-router.config.ts
// Step 1: Enable middleware
export default {
future: {
unstable_middleware: true,
},
};
// No step 2! That's it!
Behind the scenes, React Router will generate the corresponding declare module
into .react-router/types
. Currently this is done in .react-router/types/+register.ts
but this is an implementation detail that may change in the future.
react-router
- Added a new routeDiscovery
option in react-router.config.ts
to configure Lazy Route Discovery behavior (#13451)
react-router
- Add support for route component props in createRoutesStub
(#13528)
This allows you to unit test your route components using the props instead of the hooks:
let RoutesStub = createRoutesStub([
{
path: "/",
Component({ loaderData }) {
let data = loaderData as { message: string };
return <pre data-testid="data">Message: {data.message}</pre>;
},
loader() {
return { message: "hello" };
},
},
]);
render(<RoutesStub />);
await waitFor(() => screen.findByText("Message: hello"));
@react-router/dev
- Automatic types for future flags (#13506)
You may notice this list is a bit larger than usual! The team ate their vegetables last week and spent the week squashing bugs to work on lowering the issue count that had ballooned a bit since the v7 release.
react-router
- Fix react-router
module augmentation for NodeNext
(#13498)react-router
- Don't bundle react-router
in react-router/dom
CJS export (#13497)react-router
- Fix bug where a submitting fetcher
would get stuck in a loading
state if a revalidating loader
redirected (#12873)react-router
- Fix hydration error if a server loader
returned undefined
(#13496)react-router
- Fix initial load 404 scenarios in data mode (#13500)react-router
- Stabilize useRevalidator
's revalidate
function (#13542)react-router
- Preserve status code if a clientAction
throws a data()
result in framework mode (#13522)react-router
- Be defensive against leading double slashes in paths to avoid Invalid URL
errors from the URL constructor (#13510)
new URL("//", window.location.origin)
react-router
- Remove Navigator
declaration for navigator.connection.saveData
to avoid messing with any other types beyond saveData
in user land (#13512)react-router
- Fix handleError
params
values on .data
requests for routes with a dynamic param as the last URL segment (#13481)react-router
- Don't trigger an ErrorBoundary
UI before the reload when we detect a manifest version mismatch in Lazy Route Discovery (#13480)react-router
- Inline turbo-stream@2.4.1
dependency and fix decoding ordering of Map
/Set
instances (#13518)react-router
- Only render dev warnings during dev (#13461)react-router
- Short circuit post-processing on aborted dataStrategy
requests (#13521)
Cannot read properties of undefined (reading 'result')
@react-router/dev
- Support project root directories without a package.json
if it exists in a parent directory (#13472)@react-router/dev
- When providing a custom Vite config path via the CLI --config
/-c
flag, default the project root directory to the directory containing the Vite config when not explicitly provided (#13472)@react-router/dev
- In a routes.ts
context, ensure the --mode
flag is respected for import.meta.env.MODE
(#13485)
import.meta.env.MODE
within a routes.ts
context was always "development"
for the dev
and typegen --watch
commands, but otherwise resolved to "production"
. These defaults are still in place, but if a --mode
flag is provided, this will now take precedence.@react-router/dev
- Ensure consistent project root directory resolution logic in CLI commands (#13472)@react-router/dev
- When executing react-router.config.ts
and routes.ts
with vite-node
, ensure that PostCSS config files are ignored (#13489)@react-router/dev
- When extracting critical CSS during development, ensure it's loaded from the client environment to avoid issues with plugins that handle the SSR environment differently (#13503)@react-router/dev
- Fix "Status message is not supported by HTTP/2" error during dev when using HTTPS (#13460)@react-router/dev
- Update config when react-router.config.ts
is created or deleted during development (#12319)@react-router/dev
- Skip unnecessary routes.ts
evaluation before Vite build is started (#13513)@react-router/dev
- Fix TS2300: Duplicate identifier
errors caused by generated types (#13499)href
(.react-router/types/+register.ts
), causing type checking errorsā ļø Unstable features are not recommended for production use
react-router
- Fix a few bugs with error bubbling in middleware use-cases (#13538)@react-router/dev
- When future.unstable_viteEnvironmentApi
is enabled, ensure that build.assetsDir
in Vite config is respected when environments.client.build.assetsDir
is not configured (#13491)create-react-router
react-router
@react-router/architect
@react-router/cloudflare
@react-router/dev
@react-router/express
@react-router/fs-routes
@react-router/node
@react-router/remix-config-routes-adapter
@react-router/serve
Full Changelog: v7.5.3...v7.6.0
FAQs
Declarative routing for React web applications
The npm package react-router-dom receives a total of 10,813,181 weekly downloads. As such, react-router-dom popularity was classified as popular.
We found that react-router-dom demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Ā It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The MCP community is launching an official registry to standardize AI tool discovery and let agents dynamically find and install MCP servers.
Research
Security News
Socket uncovers an npm Trojan stealing crypto wallets and BullX credentials via obfuscated code and Telegram exfiltration.
Research
Security News
Malicious npm packages posing as developer tools target macOS Cursor IDE users, stealing credentials and modifying files to gain persistent backdoor access.