Skip to the content.

Part 5. react-router-dom 1/2

react-router-dom is a collection of navigational components.

These components allows us to develope a single-page web application with navigation without re-rendering the page during user navigation. These components calls the necessary components to display the required information in the application.

Install react-router-dom npm package

  1. Open a commandline at the root of the project.
  2. Run command npm install react-router-dom@6.4.2
    • @6.4.2 represents the package version
    • Warning! If there comes a warning about vulnerabilities, DON’T try to fix them using any - Audit fix - commands, since those errors will not affect to your final React app, but fixing breaks the current React version.
    • Start the npm server again npm run start

Import react-router-dom

  1. Open index.tsx
  2. Import react-router-dom components
import {
  BrowserRouter,
  Routes,
  Route,
} from "react-router-dom";

HTML

Replace all the HTML in the component with the code below

   <React.StrictMode>
    <BrowserRouter>
      <Routes>
        <Route path='/' element={<App />}></Route>
        <Route path='/example' element={<SomeExampleComponent />} />
        <Route path='/first' element={<MyFirstComponent />} />
      </Routes>
    </BrowserRouter>
  </React.StrictMode>

STYLES

  1. Create a new style file index.module.scss in your src folder where your index.tsx file is.
  2. Create a new styleclass body,
    • set margin to 0.
  3. In index.tsx, import your index styles import ./index.module.scss
  4. Note! Your code will display some errors in index.tsx, unless you have have imported the missing components. Move your mouse over the error and use Quick Fix to add the correct imports.
  5. Now you can test your new links localhost:3000/, localhost:3000/example, localhost:3000/first

Documentations

react-router-dom

<– BACK TO PART 4 …… GO TO PART 6 (Navbar) –>