Flat Preloader Icon

Setting Up React Router

React Router is a powerful library for handling routing in React applications. It allows you to create single-page applications with navigation, without the need for page reloads. This chapter will guide you through the process of setting up React Router, from installation to creating routes and links.

1. Installation

First, you need to install the react-router-dom package. This package contains the components and hooks needed for web-based applications.
				
					npm install react-router-dom

				
			

2. Basic Setup

Once you have installed react-router-dom, you need to configure it in your application. Start by wrapping your main application component with a BrowserRouter component. This component will handle the routing logic for your application.
				
					import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
);

				
			

3. Creating Routes

Next, you define the routes in your application. Routes are defined using the Route component, which maps a URL path to a specific component.
				
					import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';

const App = () => {
  return (
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
    </Switch>
  );
};

export default App;

				
			
  • Switch: The Switch component renders the first child Route that matches the current URL.
  • Route: The Route component takes two main props: path and component. The path prop defines the URL path, and the component prop defines the component to render when the path matches.