Tutorials References Exercises Videos NEW Menu
Paid Courses Website NEW

React Router

Create React App doesn't include page routing.

React Router is the most popular solution.

Add React Router

To add React Router in your application, run this in the terminal from the root directory of the application:

npm i -D react-router-dom

Folder Structure

To create an application with multiple page routes, let's first start with the file structure.

Within the src folder, we'll create a folder named pages with several files:


  • Home.js
  • Blogs.js
  • Contact.js

Each file will contain a very basic React component:


const Home = () => {
  return <h1>Home</h1>;

export default Home;


const Blogs = () => {
  return <h1>Blog Articles</h1>;

export default Blogs;


const Contact = () => {
  return <h1>Contact Me</h1>;

export default Contact;

Basic Usage

Now we will use our Router in our index.js file.


Use React Router to route to pages based on URL:


import ReactDOM from "react-dom";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import Home from "./pages/Home";
import Blogs from "./pages/Blogs";
import Contact from "./pages/Contact";

export default function App() {
  return (
        <Link to="/">Home</Link>
        <Link to="/blogs">Blog Articles</Link>
        <Link to="/contact">Contact Me</Link>

      <hr />

        <Route exact path="/">
          <Home />
        <Route path="/blogs">
          <Blogs />
        <Route path="/contact">
          <Contact />

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

Run Example »

Example Explained

We wrap our content first with <Router>.

<Link> is used to set the URL and keep track of browsing history.

Anytime we link to an internal path, we will use <Link> instead of <a href="">.

<Switch> is similar to a JavaScript switch statement. It will conditionally render the <Route> that matches the <Link> path.