Although SEI CAFE does not utilize a typical navigation bar, we'll code one as part of the infrastructure since many MERN-Stack apps will utilize one.
💪 Practice Exercise Breakout Rooms - Set Up a <NavBar> component (15 minutes)
- Create a
<NavBar>component within thecomponentsfolder. <NavBar>should render a<nav>React Element with the text "NavBar" as its only content for now.- Import
<NavBar>in App.jsx
❓ Assuming we want <NavBar> to always display when there's a logged in user and before the page-level component, where would we add it to the JSX?
Right before the <Routes>, requiring a React Fragment to wrap <NavBar> and <Routes>.
Yup, just like this:
return (
<main className="App">
{ user ?
<>
<NavBar />
<Routes>
<Route path="/orders/new" element={<NewOrderPage />} />
<Route path="/orders" element={<OrderHistoryPage />} />
</Routes>
</>
:
<AuthPage />
}
</main>
);Note the necessity to add a React.Fragment (
<>) to wrap the<NavBar>and<Routes>components.
Resulting in this for now:
❓ Assuming we want <NavBar> to render at all times regardless of whether there's a logged in user or not, where would we add it to the JSX?
Between <main> and the ternary expression.
The <Link> Component
❓ What HTML element did we use to change the URL in our previous web apps?
The <a> hyperlink element.
❓ What would happen if we used traditional HTML hyperlinks in a SPA?
It would cause a page reload when performing the navigation.
Luckily, React Router provides a <Link> component that renders hyperlinks that when clicked, change the URL client-side only without triggering an HTTP request.
Here's how we can use <Link> components in NavBar.jsx to change the route client-side:
// Don't forget the import
import { Link } from 'react-router-dom';
export default function NavBar() {
return (
<nav>
<Link to="/orders">Order History</Link>
|
<Link to="/orders/new">New Order</Link>
</nav>
);
}Clicking any of the links performs client-side routing where React Router will:
- Update the path in the address bar without causing the page to reload
- Automatically trigger a render
IMPORTANT: Inspecting the elements on the page will reveal that indeed an
<a>element is being emitted to the DOM when we use a<Link>component. However, although they look like ordinary<a>elements, React intercepts their click event thus preventing an HTTP request from being sent. However, if you accidentally use an<a>tag, React will not intercept the click event and a page reload will occur 😞
Although we've learned most there is to know about client-side routing, we will learn more in future lessons, including how to change client-side routes programmatically (via code).