DEV Community

Cover image for React Router

Posted on

React Router

Navigation is important in single page applications. One of the important libraries in React is the router library that allows us to switch between components in our application.

First thing first, I need to install the router dom:

 npm install react-router-dom@5
Enter fullscreen mode Exit fullscreen mode

After, I need to import BrowserRouter to index.js:
import { BrowserRouter } from 'react-router-dom';

If a module error about react router dom not found, I will need to install:
npm install react-router-dom --save

Then I need to wrap up the root component with a BrowserRouter tag:

    <App />
Enter fullscreen mode Exit fullscreen mode

Next, in the root component, I will import:
import { Switch, Route } from "react-router-dom"

Then I can setup the root component after the return():

function App() {

  return (
    <div className="App">
      <NavBar onChangePage={setPage} />
        <Route exact path="/">
          <Home />
        <Route path="/about">
          <About />
        <Route path="/project">
          <Project />
        <Route path="*">
          <h1>404 not found</h1>
Enter fullscreen mode Exit fullscreen mode

The "exact" in exact path makes it so that the path needs to be exactly what it is in order for it to switch pages. Notice how it is only in the home "/" part. <Routh path="*"> is a wildcard path.

Next, I need to setup the Nav component with an import:
import { Link } from "react-router-dom"
Under the hood, Link performs such as with the "a" anchor tag and onClick event listener to trigger a state change on the path route.

Then there is also:
import { NavLink } from "react-router-dom"
and with NavLink I can also set up css to indicate a link change if it is active:

nav {
  background-color: aquamarine;
  color: red;
Enter fullscreen mode Exit fullscreen mode

The return setup in the Nav component follows:

 return (
            <NavLink exact to="/">Home </NavLink>
            <NavLink to="/about">About </NavLink>
            <NavLink to="/project">Project </NavLink>
Enter fullscreen mode Exit fullscreen mode

and voila! a working Navigation bar.

Top comments (0)