Step 5

Stop your application and install react-router and the related package react-router-dom:

npm install react-router react-router-dom

Next, update index.js as follows:

  import ReactDOM from "react-dom";
  import App from "./App";
  import {CssBaseline} from "@material-ui/core";
+ import { BrowserRouter as Router } from "react-router-dom";

  ReactDOM.render(
-   <>
+   <Router>
      <CssBaseline />
      <App />
-   </>  
+   </Router>,
    document.getElementById("root")
  );

Notice the <Router> component wraps your <App /> (and <CssBaseline />).

The <Router> component uses the Web history API to keep the app pages in sync with the URL.

Next, open the App.js file and remove the changePage method from the App component and the showHomepage property from its state. Then, import the following components from react-router:

import { Route, Switch } from "react-router";

Update the render method of App component:

  render() {
    const { notes } = this.state;
    return (
      <Container>
        <Switch>
          <Route exact path="/">
            <DisplayNotes notes={notes} deleteNote={this.deleteNote} />
          </Route>
          <Route path="/add">
            <AddNote />
          </Route>
        </Switch>
      </Container>
    );
  }

The <Switch> component looks through all its children <Route> elements and renders the first one whose path matches the current URL.

Save the files and run the application. Open http://localhost:3000 to view it in the browser. Then update the URL to http://localhost:3000/add to navigate to the AddNote page. Use the browser's back button to return to the homepage.

Notice how react-router keeps the URL up to date as you navigate through the app. It preserves the browser history, making sure things like the back button and bookmarks work correctly.

Resources