navigate in react router dom
React Router DOM provides two primary mechanisms for programmatic navigation: the
useNavigate hook and the Navigate component. Code
import { useNavigate } from 'react-router-dom';
function MyComponent() {
const navigate = useNavigate();
const handleClick = () => {
navigate('/dashboard'); // Navigates to the /dashboard path
};
const handleLoginSuccess = () => {
navigate('/home', { replace: true }); // Navigates to /home and replaces the current history entry
};
const goBack = () => {
navigate(-1); // Navigates back one step in browser history
};
return (
<button onClick={handleClick}>Go to Dashboard</button>
);
}
Code
import { Navigate } from 'react-router-dom';
function ProtectedRoute({ isAuthenticated }) {
if (!isAuthenticated) {
return <Navigate to="/login" replace />; // Redirects to /login if not authenticated
}
return <div>Protected content</div>;
}
Key Differences: