React Router - rs-hash/Learning GitHub Wiki

React Router

React Router is a popular library for handling client-side routing in React applications. It allows you to define routes, navigate between different pages, and manage the history of your application without triggering a full page reload. React Router provides a declarative way to manage your app's UI based on the URL.

Let's explore the main concepts of React Router and see how they work with sample code:

1. Installation:

To use React Router in your project, you need to install it as a dependency:

npm install react-router-dom

2. Basic Setup:

Wrap your application with the BrowserRouter component from React Router to enable client-side routing:

import React from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';

function App() {
  return (
    <Router>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/contact">Contact</Link>
          </li>
        </ul>
      </nav>
      <Switch>
        <Route path="/about">
          <About />
        </Route>
        <Route path="/contact">
          <Contact />
        </Route>
        <Route path="/">
          <Home />
        </Route>
      </Switch>
    </Router>
  );
}

function Home() {
  return <h1>Home Page</h1>;
}

function About() {
  return <h1>About Page</h1>;
}

function Contact() {
  return <h1>Contact Page</h1>;
}

export default App;

3. Route Configuration:

Use the Route component to define routes and their corresponding components. The Switch component ensures that only one route is matched at a time.

4. Navigating between Routes:

Use the Link component to create links that navigate between different routes in your application.

5. Route Parameters:

You can use route parameters to handle dynamic segments in your URLs. For example, to handle a product ID in the URL:

function ProductDetails() {
  const { productId } = useParams();
  return <h1>Product ID: {productId}</h1>;
}

6. Programmatic Navigation:

You can use the useHistory hook to perform programmatic navigation to different routes:

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

function MyComponent() {
  const history = useHistory();

  const handleButtonClick = () => {
    history.push('/new-route');
  };

  return <button onClick={handleButtonClick}>Go to New Route</button>;
}

React Router provides many other features, such as nested routes, route guards, and query parameters. By mastering React Router, you can create a smooth and interactive user experience in your React applications, with seamless navigation and URL handling.

URL parameters

URL parameters are placeholders in your URL that capture specific values as part of the URL path. These parameters are often used to identify a specific resource or page within your application.

Here's an in-depth explanation of how React Router handles URL parameters in functional components, along with a code example:

  1. Defining Routes with Parameters:

    To define routes with parameters, you use a colon (:) followed by the parameter name in the route path. For example:

    import { BrowserRouter as Router, Route } from 'react-router-dom';
    import UserProfile from './UserProfile';
    
    const App = () => {
      return (
        <Router>
          <Route path="/user/:username" component={UserProfile} />
        </Router>
      );
    };
    
    export default App;
  2. Accessing URL Parameters:

    In the receiving component, you can access the URL parameters using the useParams hook from the react-router-dom package:

    import React from 'react';
    import { useParams } from 'react-router-dom';
    
    const UserProfile = () => {
      const { username } = useParams();
    
      return (
        <div>
          <h2>User Profile: {username}</h2>
          {/* Fetch user data using the username */}
        </div>
      );
    };
    
    export default UserProfile;

    In this example, the useParams hook provides an object with key-value pairs for each parameter specified in the route. In this case, the parameter is username, so we destructure it from the returned object.

  3. Navigating with Parameters:

    To navigate to a route with parameters, you can use the Link component from React Router:

    import React from 'react';
    import { Link } from 'react-router-dom';
    
    const UsersList = () => {
      return (
        <ul>
          <li><Link to="/user/john">John</Link></li>
          <li><Link to="/user/susan">Susan</Link></li>
        </ul>
      );
    };
    
    export default UsersList;

    Here, clicking on the links will navigate to the UserProfile component with the respective username as a parameter.

React Router automatically parses the URL and matches it with the defined routes. When a route with parameters is matched, React Router provides the parameter values to the component using the useParams hook. This allows you to dynamically render components based on the URL and use the parameter values for data fetching, rendering, or any other logic you need.

⚠️ **GitHub.com Fallback** ⚠️