DEV Community

Md Yusuf
Md Yusuf

Posted on

Getting Started with React Router: A Beginner's Guide

React Router is a library for managing navigation in React applications. It enables you to create dynamic and single-page applications (SPAs) with routes. Here are the basics of React Router:

1. Installation

First, install the react-router-dom package:

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

2. Setting Up Routes

To create routes, wrap your components with BrowserRouter and use Routes and Route to define paths.

Example:

import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </Router>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

3. Linking Between Routes

Use the Link component to navigate between pages without refreshing.

Example:

import { Link } from 'react-router-dom';

function Navbar() {
  return (
    <nav>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
    </nav>
  );
}
Enter fullscreen mode Exit fullscreen mode

4. Route Parameters

You can create dynamic routes using parameters.

Example:

<Route path="/user/:id" element={<User />} />

// Access the parameter inside the component:
import { useParams } from 'react-router-dom';

function User() {
  const { id } = useParams();
  return <h1>User ID: {id}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

5. Redirecting

To programmatically navigate, use useNavigate().

Example:

import { useNavigate } from 'react-router-dom';

function Login() {
  const navigate = useNavigate();

  const handleLogin = () => {
    // Perform login logic
    navigate('/dashboard');
  };

  return <button onClick={handleLogin}>Login</button>;
}
Enter fullscreen mode Exit fullscreen mode

These are the key basics to start working with React Router!

Top comments (0)