Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

React Router Basics

1. What is React Router?

React Router is a standard library for routing in React applications. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps UI in sync with the URL.

Note: React Router is primarily used for single-page applications (SPAs).

2. Installation

To install React Router, you need to run the following command:

npm install react-router-dom

3. Basic Usage

3.1. Setting Up Routes

To set up basic routing, you will need the following components:

  • BrowserRouter
  • Route
  • Link

Here's an example of how to set up basic routes:


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

const Home = () => 

Home

; const About = () =>

About

; function App() { return ( ); } export default App;

4. Dynamic Routing

Dynamic routing is used when you want to render a component based on the parameters in the URL. For example:


const User = ({ match }) => 

User ID: {match.params.id}

;

5. Nested Routes

Nested routes allow you to define routes within other routes. This is useful for creating layouts or specific views under a parent route. For example:


const Dashboard = () => (
    

Dashboard

);

6. FAQ

What is the difference between BrowserRouter and HashRouter?

BrowserRouter uses the HTML5 history API to keep the UI in sync with the URL, while HashRouter uses the hash portion of the URL.

Can I use React Router with a server-side rendering?

Yes, React Router can be used with server-side rendering, but it requires additional setup to ensure that the routes are correctly matched on the server side.