URL Formatting and Routing in React - A Guide to Using React Router

In a React application, URL formatting and routing play a crucial role in navigating pages and displaying corresponding content. To manage routing in React, we can use the React Router library. Here is a basic guide on how to use React Router to format URLs and handle routing in your React application.

 

Install React Router

Open your project directory in the terminal and run the following command to install React Router: npm install react-router-dom

Import the necessary components from React Router into your React component.

 

Define Routes

Use the <BrowserRouter> component to wrap your React application and set a base URL format.

Use the <Route> component to define routes in your application.

Example:

import { BrowserRouter, Route } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/products" component={Products} />
    </BrowserRouter>
  );
}

 

Define Links

Use the <Link> component to create navigation links in your application.

Example:

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

function Navigation() {
  return (
    <nav>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
        <li>
          <Link to="/products">Products</Link>
        </li>
      </ul>
    </nav>
  );
}

 

Access Path Parameters

Use the <Route> component with a path attribute in the format /users/:id to access path parameters.

Within the component defined by the <Route>, you can use useParams() to access the values of path parameters.

Example:

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

function User() {
  const { id } = useParams();

  return <div>User ID: {id}</div>;
}

 

Use Switch and Redirect

Use the <Switch> component to only render the first route that matches the path.

Use the <Redirect> component to redirect users from one specified path to another.

Example:

import { Switch, Route, Redirect } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/products" component={Products} />
        <Redirect to="/" />
      </Switch>
    </BrowserRouter>
  );
}

 

These are some basic concepts of URL formatting and routing in React using React Router. By utilizing React Router, you can create flexible React applications with the ability to navigate and display various content based on the URL.