Adding React Router to Material UI

Today we're going to follow our own react router example to add React Router to our Material UI project. Please check out that example as this lesson follows that structure.

App.js now looks significantly different than the previous lesson. Instead of our App having Layout and theme setup, now our App has a BrowserRouter as the top-level component, with Routes and then individual Route components for each page.

Layout.js now contains all of the theme setup, toggleDrawer, and main components. Most crucially though- in Layout.js, instead of rendering what we had previously (called MainContent, the dashboard), now we are rendering an <Outlet/>. This component from react-router-dom tells React router where the render child routes. If we circle back to App.js, you'll see we render element={<Layout/>} in the top-level route. This tells our app to always render the Layout component, and render any child routes inside <Outlet/>.

So, clicking on the sidebar, you'll see Missions goes to the missions route, and renders the Missions component. But it keeps the rest of the App in-tact. You can expand / collapse the sidebar, change routes, and React Router will be smart enough to only re-render the inner component, while changing the URL. So all of our state is still the same from the Layout component, it remembers that we are in light / dark theme as you change routes.

Using Material UI button as a react router Link

In our listItems.js, the link items that render in the Sidebar, we see that we are rendering <ListItemButton to="/" component={Link}/>. Using the magic of Material UI's "component" prop, we are using a react router link styled as Material UI's ListItemButton. This is so we can use that button as our link component, instead of React Router's Link, which would have native Link styles (blue and underlined).

Menu
Lesson 6/6
import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Dashboard from "./Dashboard";
import Layout from "./Layout";

function Missions() {
  return <div> Missions </div>;
}

function Passengers() {
  return <div> Passengers </div>;
}

function Reports() {
  return <div> Reports </div>;
}

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route element={<Layout />}>
          <Route index element={<Dashboard />} />
          <Route path="missions" element={<Missions />} />
          <Route path="passengers" element={<Passengers />} />
          <Route path="reports" element={<Reports />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

export default App;