DEV Community

Cover image for React Router: Basics
Rajat Gupta
Rajat Gupta

Posted on • Originally published at rajatgupta.net

React Router: Basics

Let's get the party started.

If you have not used react-router before most probably you are using server-side routing. If you don't know what's server side routing, see the below example:

1.gif

As you could see there is a splash of the white screen when we move to different pages. This is because every time the user clicks on a link, the request goes to the server and the requested page is sent by the server to the client machine. This process takes some time and is called server-side rendering.

When we use React Router there is no splash of the white screen since the pages we need are already on the client machine and this is called Single Page Application (SPA). SPA is like your mobile or desktop app. It has a very native feeling, It feels super fast and gives the best user experience. Most importantly SPA for browsers can only be written in JavaScript. That's why you guys are in such high demand 😉.

now, let's move to code: Our app will have 3 pages namely Home, Product, and Cart (in pages folder). Now, let's see the initial code inside index.js, App.js, and the 3 pages.

//index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
      <App />
  </StrictMode>,
  rootElement
);
Enter fullscreen mode Exit fullscreen mode
//App.js

import Home from "./pages/Home";
import Product from "./pages/Product";
import Cart from "./pages/Cart";

export default function App() {
  return (
    <div className="App">

    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
//pages/Home.js

export function Home() {
  return (
    <div>
      <p>Welcome to the home page.</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
//pages/Product.js

export function Products() {
  return (
    <div>
      <p>Check out the awesome our awesome products.</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
//pages/Cart.js

export function Cart() {
  return (
    <div>
      <p>I am the cart. Checkout now!</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Now, In order to use react-router, you have to add react-router-dom dependency. You can install it by running the below command in command prompt.

$ npm install react-router-dom@6
Enter fullscreen mode Exit fullscreen mode

Now, let's apply react-router to index.js and App.js:

//index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </StrictMode>,
  rootElement
);
Enter fullscreen mode Exit fullscreen mode

Above, wee did 3 things, just 3 no big deal.

  1. added React Router Dom as dependency.

  2. imported { BrowserRouter } from "react-router-dom".

  3. wrapped our inside , so that we could perform all browser operations on our App. (similar to ContextProvider: ignore, if you don't know about it)

//App.js

import { Home } from "./pages/Home";
import { Product } from "./pages/Product";
import { Cart } from "./pages/Cart";
import { Route, Routes } from "react-router-dom";

export default function App() {
  return (
    <div className="App">
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/product-page" element={<Product />} />
        <Route path="/awesome-cart" element={<Cart />} />
      </Routes>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

What we did in App.js

  1. Imported Home, Product and Cart page.

  2. Imported { Route, Routes } from "react-router-dom";

  3. Gave 3 Route inside the Routes tag.

    a)<Route path="/" element={<Home />} /> means that whenever in our URL we add "/", the page (or component) will be rendered.

    b) <Route path="/product-page" element={<Product />} /> means that whenever we add "/product-page" to our URL, the Product page will be rendered.

    c) and similarly <Route path="/awesome-cart" element={<Cart />} /> means that whenever we add "/awesome-cart" to the URL, the Cart page will be rendered.

Let's see the above code in action:

2.gif

You can see above that as we assign different paths (from App.js), different page (or component) is being rendered.

Now one thing that many you might be thinking "but the user won't edit the URL manually", he or she will prefer clicking on a link to get to any page. So, let's solve this problem.

//App.js


import { Home } from "./pages/Home";
import { Product } from "./pages/Product";
import { Cart } from "./pages/Cart";
import { Route, Routes, Link } from "react-router-dom";

export default function App() {
  return (
    <div className="App">
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/product-page" element={<Product />} />
        <Route path="/awesome-cart" element={<Cart />} />
      </Routes>

      <Link to="/">Home</Link>
      <Link to="/product-page">Product</Link>
      <Link to="/awesome-cart">Cart</Link>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Did 2 changes in the App.js code.

  1. imported {Link} from "react-router-dom".
  2. added 3 Link tags.

Here's what will happen: As soon as the user clicks on Product, the Link tag will take him to the URL (/product-page) given in the "to" attribute, and in the Route tag above, we can see that this path is corresponding to the {<Product/>} element and hence, the Product page will be rendered.

A similar process will ensue after clicking on Home and Cart as well. See the below gif:
3.gif

(You can style the above page)

One more thing: we can give a link inside another link. Let's give the Cart link inside of the Product page.

//App.js

import { Home } from "./pages/Home";
import { Product } from "./pages/Product";
import { Cart } from "./pages/Cart";
import { Route, Routes, Link } from "react-router-dom";

export default function App() {
  return (
    <div className="App">
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/product-page" element={<Product />} />
        <Route path="/awesome-cart" element={<Cart />} />
      </Routes>

      <Link to="/">Home</Link>
      <Link to="/product-page">Product</Link>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
//pages/Product.js

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

export function Product() {
  return (
    <div>
      <p>Check out the awesome our awesome products.</p>
      <Link to="/awesome-cart">Cart</Link>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

4.gif

That's all for this blog. I am gonna teach the remaining react-router topics in the ensuing blogs. To get notified of the same, subscribe to my newsletter here.

If you have any doubt ask me in the comments section and I'll try to answer as soon as possible.

I write 3 articles related to web development every single week. Subscribe to my newsletter (It's free) here, if you are learning the same.

Twitter: @therajatg

PS: show some love by giving a thumbs up.

Originally published at https://rajatgupta.net/

Top comments (2)

Collapse
 
rocampocastro604 profile image
Ricardo Ocampo • Edited

You forgot to show how to add the react router dependency.
$ npm install react-router-dom@6
reactrouter.com/docs/en/v6/getting...

Cool tutorial, thanks!

Collapse
 
therajatg profile image
Rajat Gupta

Thanks for reading. I added the dependency part. Thanks.