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
- Open a commandline at the root of the project.
- 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
- Open index.tsx
- 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
- Create a new style file
index.module.scss
in your src folder where your index.tsx file is. - Create a new styleclass
body
,- set margin to 0.
- In index.tsx, import your index styles
import ./index.module.scss
- 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.
- Now you can test your new links
localhost:3000/
,localhost:3000/example
,localhost:3000/first