When learning React, you might have wondered how your web application can have multiple pages. In a traditional HTML and CSS-based website, you simply create multiple .html files and link them together. However, in React, you cannot proceed that way.

One issue with having multiple HTML pages and navigating through an app like that is that every time you move to a different page, you must download the .html file for that page. The reason we have only one HTML file in React is that it downloads all the JavaScript inside of just one HTML file, making it more efficient and faster for you to navigate.

How to Access React Router DOM 📍

In React, we use an external library called react-router-dom to manage routing. You can install this library using the following command: npm install react-router-dom

The way we structure our project with react-router-dom is different from traditional web development. Below, we outline how to specify paths for different pages using routes in React.

Setting Up React Router 🚦

  1. Importing BrowserRouter and Routes First, you need to import BrowserRouter, Routes, and Route from react-router-dom in your main application file (usually App.js or index.js).

    import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
    
  2. Creating Route Components: Next, create components for each page you want to navigate to.

    // Home.js
    const Home = () => {
      return <h1>Home Page</h1>;
    };
    export default Home;
    
    // About.js
    const About = () => {
      return <h1>About Page</h1>;
    };
    export default About;
    
    // Contact.js
    const Contact = () => {
      return <h1>Contact Page</h1>;
    };
    export default Contact;
    
  3. Setting Up Routes: In your main application file, wrap your components with the Router component and define routes using the Routes and Route components.

    import React from 'react';
    import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
    import Home from './Home';
    import About from './About';
    import Contact from './Contact';
    
    const App = () => {
      return (
        <Router>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
            <Route path="/contact" element={<Contact />} />
          </Routes>
        </Router>
      );
    };
    
    export default App;
    

Detailed Explanation 🔍

Conclusion

By setting up routes in this way, you can navigate between different pages or views in your React application without reloading the entire application. This results in a smoother and faster user experience, as the necessary components are dynamically rendered based on the current URL, and only the parts of the page that need to change are updated.