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
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:
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
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} />
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/project">
<Project />
</Route>
<Route path="*">
<h1>404 not found</h1>
</Route>
</Switch>
</div>
);
}
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 a.active {
background-color: aquamarine;
color: red;
}
The return setup in the Nav component follows:
return (
<nav>
<NavLink exact to="/">Home </NavLink>
<NavLink to="/about">About </NavLink>
<NavLink to="/project">Project </NavLink>
</nav>
)
and voila! a working Navigation bar.
Top comments (0)