React Router Navigation: useNavigate()

useNavigate() for Button-Based Navigation

The useNavigate() hook in React Router allows you to navigate programmatically instead of using <Link>. "navigate programmatically" means changing the route (or URL) inside your code, not by clicking a link or a button. This is useful when:

React Router: Navigating Between Pages Using useNavigate

This code demonstrates how to use React Router for client-side navigation between a Home page and an About page using the useNavigate hook. The App component wraps the application in BrowserRouter, defines routes with Routes and Route, and allows users to navigate between pages using buttons that trigger navigate() within functional components.
        
           import { BrowserRouter, Routes, Route, useNavigate } from "react-router-dom";
    
            function Home() {
              const navigate = useNavigate(); // Must be inside a function component
            
              return (
                <div>
                  <button style={{ margin: "20px" }} onClick={() => navigate("/about")}>Go to About</button>
                  <h1>Home Page</h1>
                </div>
              );
            }
            
            function About() {
              const navigate = useNavigate(); // Must be inside a function component
            
              return (
                  <div>
                    <button style={{ margin: "20px" }} onClick={() => navigate("/")}>Go to Home</button>
                    <h1>About Page</h1>
                  </div>
                );
            }
            
            function App() {
              return (
                <BrowserRouter> {/* Wrap the entire app inside BrowserRouter */}
                  <Routes>
                    <Route path="/" element={<Home />} />
                    <Route path="/about" element={<About />} />
                  </Routes>
                </BrowserRouter>
              );
            }
            
            export default App;
                
            

Navigate Back and Forward

                
                const navigate = useNavigate();
                <button onClick={() => navigate(-1)}>Go Back</button>  {/* Navigate back */}
                <button onClick={() => navigate(1)}>Go Forward</button> {/* Navigate forward */}
                
            

Form submission + navigate() example

1. Create the Dashboard.js page

            
        function Dashboard() {
          return (
            <div style={{ textAlign: 'center', marginTop: '50px' }}>
              <h1>Welcome to the Dashboard 
&#x1F389;
</h1> </div> ); } export default Dashboard;

2. Create the LoginForm.js component

            
        import { useState } from 'react';
        import { useNavigate } from 'react-router-dom';
        
        function LoginForm() {
          const [username, setUsername] = useState('');
          const [password, setPassword] = useState('');
          const navigate = useNavigate();
        
          const handleSubmit = (e) => {
            e.preventDefault();
        
            // Simple login check
            if (username === 'admin' && password === '1234') {
              alert('Login Successful!');
              navigate('/dashboard');
            } else {
              alert('Invalid Credentials');
            }
          };
        
          return (
            <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', width: '200px', margin: '50px auto' }}>
               <input
                type="text"
                placeholder="Username"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                style={{ marginBottom: '10px' }}
              />
               <input
                type="password"
                placeholder="Password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                style={{ marginBottom: '10px' }}
              />
               <button type="submit">Login </button>
             </form>
          );
        }
        
        export default LoginForm;
            
        

3. Create your App.js

            
        import { BrowserRouter, Routes, Route } from 'react-router-dom';
        import LoginForm from './LoginForm';
        import Dashboard from './Dashboard';
        
        function App() {
          return (
            <BrowserRouter>
            <Routes>
              <Route path="/" element={<LoginForm />} />
              <Route path="/dashboard" element={<Dashboard />} />
            </Routes>
            </BrowserRouter>      
          );
        }
        
        export default App;