React Router


Create a React App does not include a page route.

React Router is a very popular solution.


React Router

To add React Router to your app, apply this conclusion from the app's root directory:


npm i -D react-router-dom


Folder Structure

To create a multi-page router application, let's start with the file structure.

Within the src folder, we will create a pages folder with several files:

src\pages\:

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

Each file will contain a basic portion of React:


Home.js:

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

Blogs.js:

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

Contact.js:

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


Basic usage

We will now use our Router in the index.js file.


Example

Use React Router to route to pages based on URL:

Home.js

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 (
                <Router>
                  <div>
                    <Link to="/">Home</Link>
                  </div>
                  <div>
                    <Link to="/blogs">Blog Articles</Link>
                  </div>
                  <div>
                    <Link to="/contact">Contact Me</Link>
                  </div>
            
                  <hr />
            
                  <Switch>
                    <Route exact path="/">
                      <Home />
                    </Route>
                    <Route path="/blogs">
                      <Blogs />
                    </Route>
                    <Route path="/contact">
                      <Contact />
                    </Route>
                  </Switch>
                </Router>
              );
            }
            
ReactDOM.render(<App />, document.getElementById("root"));
            

Example Explained

We wrap our content first with <Router>.

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

Whenever we connect to the internal path, we will use the <link> instead of <a href="">.

<Switch> is like a JavaScript switch statement. It will provide a 'Route>' s condition similar to the <Link> path.