# Error: Invariant failed: You should not use <Link> outside a <Router>

- **ID:** `react/invariant-failed-router-outside`
- **Domain:** react
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 90%

## Root Cause

A React Router component (e.g., Link, NavLink, useNavigate) is used outside of a Router context provider, typically due to missing or misordered Router wrapper in the component tree.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| React Router v5.x | active | — | — |
| React Router v6.x | active | — | — |
| React 16.8+ | active | — | — |
| React 18.x | active | — | — |

## Workarounds

1. **Wrap your app or the relevant component tree with a Router (e.g., BrowserRouter) at the top level. Example: import { BrowserRouter } from 'react-router-dom'; function App() { return (<BrowserRouter><YourRoutes /></BrowserRouter>); }** (95% success)
   ```
   Wrap your app or the relevant component tree with a Router (e.g., BrowserRouter) at the top level. Example: import { BrowserRouter } from 'react-router-dom'; function App() { return (<BrowserRouter><YourRoutes /></BrowserRouter>); }
   ```
2. **If using nested routes, ensure each route's component can access the router context; avoid rendering Link in a component that is not inside a Route or Router.** (90% success)
   ```
   If using nested routes, ensure each route's component can access the router context; avoid rendering Link in a component that is not inside a Route or Router.
   ```
3. **For testing, wrap components with MemoryRouter or StaticRouter to provide the routing context. Example: render(<MemoryRouter><Link to='/'>Home</Link></MemoryRouter>);** (85% success)
   ```
   For testing, wrap components with MemoryRouter or StaticRouter to provide the routing context. Example: render(<MemoryRouter><Link to='/'>Home</Link></MemoryRouter>);
   ```

## Dead Ends

- **Importing Router from 'react-router' instead of 'react-router-dom'.** — React Router v5+ has separate packages; the Router component is in 'react-router-dom' for web apps, and using the wrong import may not provide the correct context. (70% fail)
- **Wrapping only the Link component with a Router, but leaving other parts of the app outside.** — The Router must wrap the entire part of the tree that uses routing; partial wrapping can cause other routing components (like useParams) to fail. (80% fail)
- **Using BrowserRouter but forgetting to install 'react-router-dom' and relying on a global script.** — Without proper npm installation, the import may fail or resolve to a different version, leading to context mismatch. (90% fail)
