React Router doesn't provide direct navigation capabilities outside components, but you can use these approaches:
1. Create a Navigation Utility
// navigation.js
let navigator;
export const setNavigator = (nav) => {
navigator = nav;
};
export const navigate = (to) => {
if (navigator) {
navigator(to);
}
};
2. Initialize in a Component
// App.jsx
import { useNavigate } from 'react-router-dom';
import { setNavigator } from './navigation';
function App() {
const navigate = useNavigate();
setNavigator(navigate);
// ... rest of your app
}
3. Use in Utility Functions
// authUtils.js
import { navigate } from './navigation';
export function login() {
// Auth logic...
navigate('/dashboard'); // Works outside components
}