Lecture Script

Summary

Action Items

Conditional Rendering Foundation

The lecture began by demonstrating conditional rendering as a foundation for understanding React Router.

React Router Concepts

React Router provides a comprehensive solution for client-side routing with URL management and browser history integration.

Router Types:

Core Components:

History API and URL Management

React Router handles browser history management automatically using the History API.

Implementation Demo

The lecture demonstrated converting a basic React app to use React Router.

Installation and Setup:

Converting Links:

Setting Up Routes:

Dynamic Routes and Parameters

Dynamic routes allow capturing URL segments as parameters.

Nested Routes and Outlets

Nested routes allow hierarchical URL structures with parent and child routes.

Switching from HashRouter to BrowserRouter

The demo showed how easy it is to switch router types.

Programmatic Navigation

The useNavigate hook enables programmatic navigation without user clicks.

Notes

Transcript

For this case, just representing it by a string is going to work fine.

Okay, so now we have a way to keep track of the page that we want to show. Now we want to say, well how do we conditionally render that page? So Another thing to remember is any reactWhere a component is a function or a class that optionally takes props, we're not taking any props in this. Care about props at this time, for the police for this? And then. Returns a reactant element. So the return statements here typically always return some kind of JSX structure of nested components.

So What we can do here is we can say, OK, let's create a variable. Current page, called current page. Let's declare, declare our variable called current page. And that variable-It's going to hold some. At a very first glance, you may be like, well, we are keeping track of the current page in the state variable. And we are. But what current PAGE is actually going to I probably should name it different, but we'll just keep it current page.

It's actually going to hold what is the current content you want to show. Let's look at one way to do it. So now we can say, Okay, let's createE. Switch statement. You could use it if else statements too, if you wanted to. In this case, the switch is going to be a little more efficient because we're dealing with strings. Part of the reason why I said we're going to use a string here. I'm using a switch here because I think And I'm doing it this way because I think this Mentally.

aligns with how React, or React Browder, kind of, how you can pick them up in React Browder. So, we're gonna use a switch state. Today's switch. On page So the switch statement is going to be using the value that's currently in state. Now we're going to have a case. That is...

How that could be one strategy for doing browning. And then usually with the switch, we always want a default case. And we're going to have something different. We don't need a break. Okay, so now this switch Is going to Do something based on that value in state. And what we're going to do, because we Because a React JSX element can be stored in a variable. So I'm going to come in here and say, If the case is home page, We're going to set current page equalSchool two, four.

Set two.

Our home page.

All right, so now... You'll see why I did the conditional rendering this way. What we're gonna do is we're gonna come down here, Underneath the nav element Put our curly braces in to evaluate JavaScript. And then Put the current page variable. Because that current page variable holds, TheUm. Key component. We can just say, render that component here. Now we actually want this inside of demo.

So basically just saying, rendering this spot Whatever component is currently set. So as soon as we call set page with a different string, it's going to re-render the component. It's going to look at the switch. It's going to put the different component into that variable and then render that different component here.

All right, so now we have this. So you can see clicking these do nothing. Right? But we are seeing-Home page, because that's the default state that we have. If I come into the React developer tools, I'm sure I have them installed in this browser. Comments? When we go to app, we can see what the state's set to. If we change this to CSS page, You can see that React updated the site with the right form.

But as you notice, onClick is different than onClick for JavaScript. This is an actual React problem. So we're going to say, okay, in the onClick, we need to put something, and we're going to put a function. Same rules apply like any Event handler? We can't pass a parameter to an event handler. So we can't just say set page here. Like that because our set page function is expecting us to pass a string to it And The only thing that's going to get passed to this setPage function is The event.

So the way we solve this is we write an anonymous function. That's right. where the anonymous arrow function calls our function. We're defining a new function. That new function has a single line, so we don't need curly braces. And that new function calls setPageWithDistrib. So because this is declaring a function, we can pass it to onClick and now it's set up. And we would come down here and we would do the same thing to each of these other functions.

Now, The things that you'll see that are problems. There's nothing happening in this URL. It's all just. The hash sign, because all my links have the hash sign. We could take and remove that hash sign. I'm curious if this is going to get it.

I talked on the first slide about the history API.

So there's the There's this history API you can look into.

And What this lets you do is-the history object is the browser's history. It's this keeping track of where it's been. If you use the push state, It will Push a new URL into history. Right? So like, You can... We could take, wish I had that still open, but like as we clicked, We could say Push state, put the URL in history, and then we would see the URL arching. The replace state Here. the replace state.

What that does is it replaces the state object of the current page with this new one. And it basically Instead of adding another entry, it replaces the entry. So it basically doesn't let you go back to the page you just started. It's replacing. So depending on if you want there to be a separate page in between there, You would use push state versus replace state. And these things let you, like I said, push these entries into the history.

And then when the user hits the back button, Or if you use The history back or the history go. These pop state events will fire. So we can-There'll be these pop state events that you can listen for. And Handle those to be able toConditionally rendered something, yeah. So if you If you were We wanted to take what we just did and make it appear like the URL bar says, oh, you're on JavaScript page, you're on CSS page, you're on this.

Hit back. Yep. takes you back in history from JavaScript page to CSS page, a pop state event would happen. You would have to listen for the pop state events and push all these history state events in your JavaScript yourself. Get all those link functions and then. Global job search, if you want to manage that all yourself.

In The other thing, well, you can do all that and then as you're navigating around the app, it'll look right. But the thing that it won't solve is if somebody still reloads your page with slash. JavaScript or something? It's not going to automatically know to show the JavaScript content. You would have to build it to the JavaScript of your page and your conditional rendering is something that looks at the We know location, path name, makes the determination when the page loads or what to show.

There's a lot you have to do manually. And that's the stuff that we get And for free, we use a routing framework. It handles all that for us. With React Router, We're gonna see that there are, there's gonna be, There's a few different approaches. But there's two main routers that we're going to talk about. One is called the browser router and one is called the hash router. And I'll get into those in a minute, but it's just-It's how doesReact router handle keeping track of this and managing all this.

It also has nested routing. So you can build like... URL passed. We're going to do that in this next example where you may have a page that then has subpages. And can you render conditionally a piece of content on a subpage? Based on the full URL, even though it's a nested page from a parent page, there's all this nesting that we can do, and we can do this hierarchy. structure our files, you could take Technically, you've all your routes based on the full URL path.

That could be your entire route every time. You could do the whole thing. Or you could build it as separate segments where you have nested routes where each piece of the URL is a nested rug in the hierarchy and it just makes the app a little more Organized. So we're going to see that. Nested routing, for example. Dynamic routing. It lets us use parameters in the routes. So in the URLs, we can take any information you want.

The three we'll kind of talk about which really do the bulk of all the work. It's the browser router, the hash router, and the memory router. So we'll start with the hash drive. And this is the one we'll start with in the demo. The hash router UsesThe Hatch Stunt. In the URL. to manage state. So we know that Uh... If we had this URL and we put hash something up here. It really doesn't change the location we're on.

We're still on this page. These are traditionally also calledAcres? Because if there was an ID on the page of something, It would scroll us down to that ID, the element with that ID. They're also technically in the URL path called document fragments. So the hash router uses that to manage What pager? This will make more sense when you see it run in the image.

As you click around, the root URL stays the same. and just what's after the hash changes. You've probably all seen this in an app, but maybe never noticed it, that, oh, we're on mybank.com slash mobile banking, and then you see a pound sign with something that's changing. That's the idea. The whole app's running on one URL. The pound sign changes. track of our URLs, we can bookmark something with the pound sign because if we go back to that bookmark, it's still gonna load the native app at that URL.

and it's going to be able to look at the fragment and be able to determine what the rhetoric is. So this was the first version of how this was handled. Browser router is like the step up from there. And what BrowserRunner does is it gets rid of the hash side sign all together and it literally changes the URL that you're on. So in our browser we're going to actually see like /html /css /javascript as we move around.

It's going to look just like a normal app and as long as the web server is set up correctly You can bookmark the pages and go to any page. And the reason I say that is because In some cases, if the actual web server that's serving the single page application isn't set up correctly, it's going to look at those URLs and think that they should be directed to different resources. when they all should actually go back to the same resource and just conditionally render stuff.

What memory router is for? Is memory robbers interesting? Because this is-A router that's used to store Your entries and keep track of everything in memory instead of the URL bar or the history stick. He made me like, when would I ever use that? And... It's got a definite Like, niche, like, use case. Something that doesn't have a URL bar. So let's say your building's I think we've talked about Electron in here.

Well... Inside that web window, in that app, you don't really have a URL bar before navigating around a web page, even though the UI is being rendered by a web endpoint. That's the kind of case where you use the number. You can use that to keep track of what Part of your app you're in, but the user's never interacted with it.

Okay, so those are basically our routers. Another core component here is the route component. And the route component is a simple component. It looks like this. Looks like this component right here And the row component It takes two props. It takes a path. And it takes an element. There are some additional ways you can use these components, but this is like the way that it's like.

It's a problem. But anyway. Basically what this route component saysYes. If The URL I'm on matches what's in this path. render whatever component is in this element right now. If it doesn't match that path, don't do it. So it basically builds in your conditional rendering Looking at your URL. Now, these routes have to be nested inside of a router. So in this case, it's a browser router. We also have this routes component, which we'll talk about in just a second.

But this browser router is what's doing everything, so that has to be around everything. So anything in your app that you want to be aware of the routing context and doing initial routing has to be inside the router. There should only be one router in your whole app.

themselves, but the router itself is surely one. Typically, If your app is going to be using it throughout the app, it's going to probably be at the top most level of your app, wrapped around your track. And then another primary component is the link component and it's like cousin, the nav link component. And these are the components that we have to use to navigate around the app and tell the framework We're moving around again.

So you'll see something like... So this is showing a nav link component and also a link component. The only difference between the two is the NAB link component. Well... Have a class on it. If the route that thatLink 22 is the link you're on. By default, that class is just active. So it's good for making navigation because most of the time you want to style it.

But what I'm on this one is just styling it different.

But for the most part, like I said, links will be used throughout the app. Nav links will be used in the nav bar. And then if you need to programmatically move the user around, In any way, don't use like a location. sign or location replace or location href and do a redirected JavaScript ever with this.

You would just use the use navigate hook To set it up, to give you this navigate function, and then you can use this navigate function to move somewhere else. Programmatically, that'll tie into the route I'm tracking.

We talked about the route component already. That's the one that has the path and the element that you're going to render. There's also a routes component. So we saw in this example here where it was browning, They have this routes component, or here, they have this routes component that has individual routes inside of it. What is this Routes component? Well this, you can kind of think of this routes component As comparable to that switch statement we just put in that last example application.

It would technically slash login would also match just slash. Because that's in the path. So by using this route, you can kind of limited to only the first matched the best match. It's a good practice. to use this route. unless you have a need for it to be different and match different.

We'll go from the side. So we already talked about LINK and NAV LINK, so we kind of already went across that. Just think of LINK as our standard anchor tag, but we have to We use it when we're dealing with graph router. It has a to attribute, but it's the path that we want to go to.

So just remember that it just like a--The relative path.

And then this is an example of just how we use Navigate works. I'm not going to do this in our example, but basically we usually use Navigate hook then inside of our click handlers on our buttons we can programmatically navigate. This is showing some nested routes inside of BrowserOwner. So we have an index, we have a homepage that renders this layout. Inside this layout there's going to be an outlet component which is going to say, "Okay, any of your children render in the spot where the outlet is." On the index page, which is-Whatever path the parent matches on, you're going to render the element home.

Okay, so just to mention the outlets. These are The outlet, wherever you put that in your component, is where any nested children are going to run. So inside dashboard. We have stuff and then there's outlet.

That means this stats or this profile component will actually render in the dashboard componentAt this spot. Right on the side.

out of our existing project and pasted it in there. And that's where we're at. It's the exact same app. It's just from a newly generated project instead of. The only thing that would happen if I duplicated it was-Probably should have, if you want to come in here, have changed the name. So that's why I did a new. Version, but either way it'll work. Okay. So we have this as a starting point. We're going to start piecing in the React router components.

So the first thing we're going to do is we have to install dependency. So we're going to install it the way that it basically says on our docs. Big surprise. We're going to install the React router package from NPM. In Boulder, So if you found any documentation on version 6, I-Not important because we're not producing. In version six, the package was actually React-Browser DOM. But now it's all bundled together in the same React-Router package.

So if you see any older examples and say, oh, React-Router DOM, it's the old version six package. So we're going to install that package. And here, And then we're going to import-we'll import the browser router just like this, but we're going to quickly change it to a hash router. And I'm also going to do an alias on the import so that we can easily swap them out later. So come over here, and I'm going to just open the terminal here.

Okay, so we have that set up. Now we have the package. It's in here as a dependency, reactor order 7.13.1. So in App TSX, first thing we want to do is we want to import React router.

So we'll do import Um. Use the brackets to do a name dim for. Browser. Browser router from React. So basically like what it's saying to do here Now. I told you we're going to actually change this a little bit. So we're going to do two things. We're going to say... We're going to alias this. So instead of using BrowserRouter down here in the code, I'm going to just use the name Router. Because then that way if I want to swap it later, I can just change the alias.

In order to change my code, so we'll do asRobert? So now we're saying we're importing BrowserRouter, but we're locally naming it Router. And then they say, we're going to start with HashRouter.

It would have been fine because that way it's around the whole app. We'll just put it here. That way we can keep the import here and we can see it. So here I'm going to want to take and sayRouter.

Then we'll take the closing one.

It was the last week or the week before, I don't remember which week it was, we looked at use context stuff as a way to pass, I think it was last week, as a way to pass stuff around through different components. The React Router router component uses the use context link internally.

And that's how it lets route components and link components have access to what ground we're on at any point in your map. Providing a context provider for that.

We're actually not going to use the links at all, but it will be easier to refactor those. So we haveWho's calling? Okay, and then... Uh... We also can get rid of All of this. The switch statement. The content variable, so right here where we're labeling content, let's just say contentOver here.

And we can get rid of this entire switch logic. It should be a written statement. Here's the stage. Okay, so we'll get this down here. He wants to, It's telling me I'm not using these imports anymore. That's fine. The state one we actually won't use, so we can go ahead and get rid of that. But these ones we're going to actually use at some point.

So now, We're going to add Link components instead of These acres.

And So we'll see both. So we're going to change these to link components.

All right, so we've just changed some of the links. Our link component does not useIt is a tube.

Wrong. Two. Two.

We don't have the conditional rendering yet, but you can see up here in the URL bar, Remember we're using the hash router, so even at the home page, Everything is being served off the run, right? Everything's off the localhost with D173 slash, and then whatever's after the hash is the page run.

Now we want to add our conditional rendering. So where we had that content, we're going to add our rocks.

So instead of conducting here, we are going to say-We're going to put a routes component.

So our first one, we'll say route.

Self-closing. Okay, so our first row is gonna say index.

Because we want it to just renderindex of the route. We could also put here path slash That would work too, but index works because it's the root of this route. And then we say element. Equals And then inside curly braces because we're in JSX and we have to evaluate more JSX.

Now we can repeat that. We'll do one more, then I'll copy and paste. We'll say path. equals slash HTML. Element. equalsDLL page.

We have basically what we had before. But now we have the URL actually. Doing something different. We could switch out to the browser router now, but I'm going to go ahead and just leave it hash router until the end, then swap it at the end, and you'll see. I think it's valuable once we see the parameters and stuff that they worked on a hash router to. Okay, so we have that. So now let's talk about the other pieces, the dynamic routes and the parameter.

We come in here and we change these out toJust like the old mode. Changing the NAM link.

So now they're naveling. Just that change. Now if we come back here and we refresh and we'll click on HTML, look at HTML and the default behavior here isGood.

But we're getting the current class. So now we could come in here and--In at CSS.

Just here at the bottom, define a dot active. Amen. Let's do a lighter color. Man, he was too good. to regular color. Now.

Okay, so... To do this, We're going to create in our JavaScript page, I want to create some additionalNavigation.

So down here underneath the paragraph, I'll just go through all the changes that are going to come.

So... I added a H3. This is the JavaScript page component. Here are some subtopics of JavaScript. I added an unordered list with link elements that are going to, I'll explain this in just a second, to react in ES6. I've also added an outlet component to say this is where I want the nested children routes to render inside that outlet.

The only thing that's-The weird here is this user's alpha path hook.

What this does is the user's own path hook takes the path and resulted Relative to the current like path you're on. So if we're on this case, we're saying we want the current path with the period. But basically, useResolvePath is going to say, OK, when this renders, what is the two path that we're on?

We can go into the aft and build the nested rugs. So we can come down here and we're going to change this,Uh, JS? Uh, Raul? to instead of being a self-closing round, We'll change it to where I can accept children. And instead of doing the index in here, Because if I do the index in here, then it's going to render the JS as the index and it's going to render the other ones as separate components. I will actually.

So instead of doing it with the index,You could read the outline again. We'll do a route here.

An elementIs... You notice I didn't use slashes here. Slashes, but you don't have to because it's gonna build on the URLs for us. Five plus six, maybe a six, perfect.

So now that Because remember on the JavaScript page we have the output wire in, so basically saying Anything that's nested in here, when the paths match, will renderDo this.

I'm going to put colon topic.

So now that's basically saying capture this as a parameter for this URL segment and store it in the parameter called topic. And then what is it going to render?

When I refreshed on JS/Next, we're getting the "here's information about your topic." So we go back to JavaScript, it goes away. ES6 React is good. We can put anything in here. Next.

That's your S, and we get information about your time. Okay, so that's cool.

So we're getting the params. So then how do we use that param? So we're going to actually use that inside of the component and use that use params hook. So we'll come back over here. An inside topic here. We will do cuts for ends. Set to use brands.

Okay, and now we have this params object that's going to have those variables on it. Take that suggestion. So we're going to say, okay, in that spot, instead of the word topic, we're going to use the curly braces and say params.topics. Topics will be named the param. And that's all we're going to basically do for that. just to see it. And now you can see that that's coming through. Whatever we have in the URL bar, So I know that's super simple, but you can see how you can use that parameter to fetch some data from an API that's different than a different data.

You can use the prams inside your-And this is all client-side routing. Next week, when we start looking at Next, that's all going to be server-side routing.

But if you want to go back and see what the browser router looks like, you come back to app and because we aliased it, we can just change this.

Browser router. Resave and then let's justCompletely take that off and refresh the whole thing.

Now as we click through here, Everything's going to look like it's A real URL? And Also what we can do is we can copy that URLAnd let's,Open the new tab. And let's say, OK, let's do React. And next. The React router is all wired up to be able to handle this correctly. So that's why I say if your server is set up right, Using browser owners better. But let's say you're on a big website, maybe on some content management system, and all the pages have their own URLs, and then they say, okay, well we want you to deploy this little I'll just say banking and or Content creation app or something.

the URL slash app. And if you try to do multiple URLs, it's going to cause problems in the app, right? Because other pages on the site. Then I would say use the hash browser, deploy the whole app on that slash app URL on the site, and then let the hashes manage movement around your little app.

We come in here to do detail. It brings in params, use params. It also does use the use navigate hook to do some programmatic stuff. So like when the edit form is submitted, I programmatically have it moving me back to the home page. So you take a look at that stuff. If you want the details, you can look at this handout. It's a markdown file. You can preview it in here, and it'll give it to you in red.

So I'll put this one up in the In the repo tonight, the student handout will be in there. That's basically instructions. So if you wanted to take the to-dos, What you're going to have to do is local storage edit and look at this handout and try to implement it yourself to get to this point.

I think if you just search GitHub education and Google will get there. and apply as a student and get a free copilot license.

Okay, so if you have any questions about any of that stuff, let me know. Or the sentiments, I'll send out a message this weekend. We'll start next week. Yeah. There is some on the assignment slide there I would like you to read the getting started with next.

It's a small little section on the next website just so you're a little familiar with that before I start talking about it. Um.

Work on the lab. This weekend I'll send out some kind of more firm due date after I hear whether or not anyone is Any questions? And then--The question.


Demo: react-norouter

import { useState } from "react";
import "./App.css";
import HomePage from "./components/HomePage";
import HtmlPage from "./components/HtmlPage";
import CssPage from "./components/CssPage";
import JavaScriptPage from "./components/JavaScriptPage";

function App() {
  const [page, setPage] = useState("HomePage");

  let currentPage;

  switch (page) {
    case "HomePage":
      currentPage = <HomePage />;
      break;
    case "HtmlPage":
      currentPage = <HtmlPage />;
      break;
    case "CssPage":
      currentPage = <CssPage />;
      break;
    case "JavaScriptPage":
      currentPage = <JavaScriptPage />;
      break;
    default:
      currentPage = <HomePage />;
  }

  return (
    <div className="App">
      <header>
        <div className="site-name">
          An Introduction to React Conditional Rendering
        </div>
      </header>
      <nav>
        <ul>
          <li>
            <a onClick={() => setPage("HomePage")} href="#">
              Welcome
            </a>
          </li>
          <li>
            <a onClick={() => setPage("HtmlPage")} href="#">
              HTML
            </a>
          </li>
          <li>
            <a onClick={() => setPage("CssPage")} href="#">
              CSS
            </a>
          </li>
          <li>
            <a onClick={() => setPage("JavaScriptPage")} href="#">
              JavaScript
            </a>
          </li>
        </ul>
      </nav>
      <div className="content">{currentPage}</div>
    </div>
  );
}

export default App;

History API

History API (Web API; Browser API)


history.pushState(state, title, url?)

새로운 히스토리 항목을 “추가” 합니다.