Getting started with React Router 4: Create a single page application | Esteban Herrera | Skillshare

Playback Speed

  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x

Getting started with React Router 4: Create a single page application

teacher avatar Esteban Herrera, How can I help you?

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

    • 1.



    • 2.

      What are Single Page Applications?


    • 3.

      React Router


    • 4.

      Setting up the React app


    • 5.

      The Router Component


    • 6.

      The Link and NavLink Components


    • 7.

      The Route Component


    • 8.

      The Switch Component


    • 9.

      Route Render Properties


    • 10.

      Nested Routes


    • 11.

      Using Route Parameters


    • 12.

      Final Thoughts


  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.





About This Class

In this class, you’ll learn how to create a Single Page Application with React and React Router.

First, you’ll learn what are Single Page Applications and the concept of a router.

Next, you’ll learn about React Router, how to set it up and the essential components of this library to create routes, links, pages from React components, and not-found pages.

Finally, you’ll learn about nested routes and how to build routes with URL parameters.

By the end of the class, you will have the knowledge to create simple React web applications with React Router.

This class is geared toward beginners, the only prerequisite is basic knowledge of how React works and how to create a React app.

You can find the source code of the demo project on this GitHub repository.

Meet Your Teacher

Teacher Profile Image

Esteban Herrera

How can I help you?


Esteban Herrera has more than twelve years of experience in the software development industry. He has worked in many roles and projects, but mostly architecting and developing enterprise systems with Java and Javascript.

However, he also enjoys programming in iOS, Android, and VR/AR.

Nowadays, he spends all of his time learning new things, writing articles, teaching programming, and enjoying his kids

See full profile

Level: Beginner

Class Ratings

Expectations Met?
  • 0%
  • Yes
  • 0%
  • Somewhat
  • 0%
  • Not really
  • 0%

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.


1. Introduction: Hey, guys, welcome to my class. Getting a star, It would react. Drought. Therefore, my name is Esteban Herrera. I have been developing applications for more than 10 years from using plain JavaScript to library some frameworks like a query, angular and react in particular. I have no react. And this paradigm for developing Web applications in this class, you know how to create a single pressure application would react and react. Router. Single page applications are with applications that don't need a full pastry loath when their content change, like email or Twitter. This class is for beginners. You only need know, ledge off Audrey at works and how to create a react up alcove or things like what are single page applications? The concept of a rather helped to set up react rather the essential components off this library. How to create pages from react components nested route on how to build routes with Europe, parameters. By then of this class, you will have the knowledge to create simple single page react applications with react Router. This is killed is important because on one hand, single place applications provide a better user experience On On the other hand, they are easier to deploy and maintain than a traditional Web application. So let's get started 2. What are Single Page Applications?: single place applications are graph applications that dynamically load their content in a single page instead of redirecting the user toe. Other pages in a traditional way application. When you click on a button or link, the browser contacts the server and loads a whole new page, even if only a small part of the pace changes, which gives a sense off interruption, especially if the new page takes some time to love. On the other hand, a single place application only reloads the section of the pace that is going to change. The application is still contacts the server when the user requests something, but this is done in the background, using Ajax on the server instead of returning. HTML. Koth, representing a pace, returns adjacent response. Just the data that the APP needs. Neither is a good example. Off this type off application. When you click on it to it, only the tweets information is fetch from the server. The patient doesn't fully re love. The advantages are that these applications are more responsive. The user experience is more fluid. You can have loading indicators to let the users know the application is doing something, and if you design it properly. The application can handle most of the processing on the client to reduce the number of requests to the server, which could prevent network errors and improve performance. Another advantage is that most of the time these applications are just when a steamer file , good CSS and JavaScript bond does. These makes them easier to deploy because they can be uploaded to any esthetic content server. Of course, the application will need a back in to get his data, but that can be a separate application build with a completely different technology that will probably recite in another server, which improves maintain ability. However, there are also some disadvantages in a single place application. Most of the time, all the necessary coath on resources ever tree at the beginning in the initial base load. So if the up gross toe a significant size, these initial loath will be a slow search engine. Optimization S CEO could be tricky because there's only one page and the application is built dynamically, so the search boats may not girl old your side or execute JavaScript growth in a similar way. Analytic tools may not correctly track page views, since well, single pressure applications don't really contain pages. Another disadvantage is that this applications can get complex easily, so they required to be better designed than traditional applications. Tow, avoid memory leaks, security problems or other kind of problems. One of them, in particular, is browser history. As the application is contained in a single page, it cannot rely on the browsers forward and back buttons. For this reason, something that can change the Ural to push or replace your oral history events in the browser, according to the Application estate, he's neither into either. For example, notice how the Ural changes going. A tweet is clicked and how a history entry is generated. This is the job off our after A. Rather allows your application to navigate between different components changing the browser euro, modifying the browser history and keeping the U. S state in think React is a popular library for building single based applications. However, as React focuses only on building user interfaces, it doesn't have a built in solution for routing. Reactor Router is the most popular routing library for react. Let's talk about reactor after in the next lesson 3. React Router: some people think react. Router is part of the court off React Day. Yes, but actually it's an open source. Dear Party Lavery developed a maintain by react training. Moreover, REAC router is divided into three packages. Web, native and core. However, you will almost never have to work with the core package directly because it just provides the core components of react. Router. If you're working with a Web application, you should use React. Rafter Gwen. And if you're building a mobile application, would react. Native. You should use react round her native. In any case, these packages will install react Rotor Core s a dependency in this course. All focus on react Router Web. Not many things will also apply to react. Router Native Reactor out Our works with a model called Dynamic Routing where route are declared throughout the application in the place they are used. This is different. That static routing. Take this code, for example, where you have to declare the routes off your application of front aspire of your up initialization tasks before anything is rendered this way, we dynamic routing react route or handles routing on the client side of the application. The server will handle the initial route to serve the react application. But after that reoccur, Outer is going to be listening for route requested by the user to serve the Riyadh components associated with those route reactor out or doesn't recognize a certain route. The request will be passed through the server, and if it can handle it, the server would respond with a whole new page, which is useful for functionality like logging and log out. All right now, let's set up a react application and install React router. 4. Setting up the React app: All right, let's create a react application I'm going to use Create React up If you haven't used this tool Don't worry as long as you have no day Yes, and mpm installed You don't need this dollar confuse or anything else. I'm going to assume you already have these tools installed. Just make sure you have at least not burst in six You can run north Does this burst in? Don't know what person you have installed and you also need the latest version off MPM because sometimes things don't gargle You don't have a recent burst in you can run MPM does this person to know good bursting you have installed Or if you just goingto make sure to have the latest one you can run mpm Isdell npm deskee on mpm will be updated next Execute the following command mpm x create that React that up my desk react that rotor that up. MPM X is a tool that allows you to execute, not packages even if the packages are not installed locally. All right. My react wrote a rap is the name of the up this way and directory with this name will be created Great Now I'm going to see the into these directory. And since this is a great application, I'm going to still react rather dumb with MP and Mr That's the safe react rotor Dumb. At this point, you can execute MPM start on a browser window will open at local host for 3000. You shall see something like this. Okay, I'm going to up in the project in an editor. I'm using brackets, but you can use any editor you one in the file public is last index dot html after the bootstrap C. S s file. That will help me a style, the application. Then I'll go ahead and replace the content off app The CSS with my own cost honest tiles on the content off up the jail? Yes as well. When you save a file, the changes are reloaded automatically. You don't need to a stuff on Rex acute mpm mr. To see them Don't worry about the styles. An instructor of the application at this point, you can install your application in anyone you want and you can find the entire source growth off the project in this get off repository. The link is in the description of the class. For each lesson there's a branch goes, you can check out Dickov off the application reviews in that lesson. Now we're ready to use react router. But before that, let me tell you that react router is based on three components. Rather the rotor that keeps the you. I mean, think with the girl link, a nap link that renders a navigation link on route that renders a U I. Component depending on the girl. In the next lesson, you know how to integrate routes to the application with the router component. 5. The Router Component: most of the time, I don't have to use the writer component directly. You'll use one off its implementations in a Web application. You have two options. Browser Router, which uses the HTML five history, A B I and Cash Router, which uses a hash character to set the anchor part off a euro and can be accessed with a properly window dot location dot hash. If you are going to target older browsers that don't support the HTML five, his story a p A. Usually use has rather which creates euros with these former. Otherwise, you can use browser router, which creates euros without the hash. I'll use browser rotor in these demo application, so in sores, it's last index the day. Yes, I'm going to import it from React Rotterdam and use it to grab the APP component. It's important to mention that our outer component can only have one child element. For example, if I add another element when I save the file, the application will throw the photo in error. Message are other may have only one child element. Okay, I'm going to delete this extra element. As you can see, this component doesn't have any effect on the U. I. The main Gulf of a router is to create a history object to keep track of the Ural, the location when the location changes the child component off the rotor. In this case, up Israel Orender. Most of the time you use a link component to change the location. Let's talk about links in the next lesson. 6. The Link and NavLink Components: reactor out there provides the link enough link components to render length that you can use to navigate around your application. The link component, except they attribute to that takes s string that represents the location to navigate. And you can also ask Europe parameters. But did you prefer you can also pass an object with the properties, but name the path to link to Sorry. A string that represents the query parameters has a hash the boot in the euro on the state on object that represents the state, the persist to the location. Another important attribute is replaced when it's set to true, the location off the link component will replace the current entry in the browser history instead of adding a new one. On the other hand, naff Link is a special version off the limb component that at Sonny's stating attributes, which are useful for navigation menus. For example, Duerson active class name attribute that takes the name off a CSS class that will be added to the CSS classes when the element is active. In other wars, when the location off the link much is the current Ural, the phone's glass name is active or you can use the activist I'll attribute to pass a style of yet for the same purpose. Two other important attributes are exact on a strict going. Exact is set to true. The active class or style will be only applies if the location is much exactly, and one district is set to true. The three Leanness slash off a locations, but name will be taken into consideration when determining if the location matches. The current Ural deserve the most important attributes off link and no link, but you can know more about them in the Documentation off React router. All right now, let's create a navigation. Many in source slash up dodgy. Yes, I'll go ahead and replace these anchor element with a link component. I'll have two more links. 14 on about base and another one for a usurpation. Also, let's not forget to important the link component at the top off the file. Now in the browser, you shall see something like this. If you inspect the HTML code, you'll see that the lean component just generates an anchor element. However, those are in regular anchor elements. They changed the Ural without refreshing the base. If you have a regular a element to the Goethe. The patient will be fully Reno. That so remember the lean component doesn't represent a regular anchor element now. Not is that nothing happens when a link is clicked in the next lesson. Junor How to run their something with the route component. 7. The Route Component: the off the road component is to render something when the location much just a path you can define. Gladys render by using one of the following properties off the road component with the component property. It renders a component going. The location matches. The road spot would render you pass a function that returns the element or component to be rendered angry Children. You also pass a function that returns the elements or component to be rendered. The difference is that the return element is rendered no mother if the path is match or not . Each is useful in different situations, but you can only use one of these properties on a given route. Component in this lesson are so you have to use the component properly. In addition, using the PATH property, you specify anybody you're a bad this way. A new component is created using react that create element. This means that on every render, it creates a new component. Instead of just updating an existing one, the path can define by rebels, and it can be a regular expression. REAC Rotor uses the library path to reject bursting 1.7. To pursue these expressions, there's even a tool that allows you to enter a route, and it will show you the regular expression for that route, and you can also enter a path to see if it matches the route. It's very useful back to the road component. It also takes an exact properly that went through the component. Goldberg surrender only if the bad matches exactly with a strict apart that has a craziness last will only match a location with a trailing this last. If the property is true and finally, when the sensitive properly is true, it will make the matching case sensitive. Okay, Right now, in our application, the euro changes when a link is clicked. But not the u I. Let's fix that. I'm going to create a components directory and inside off it three components, one for each route. First the home component for the main route. At this point, each component will only show a message. Then you thirst for the route slash users I'm finally about for the road. It slash about now toe. Specify the Ural that corresponds to each component in source slash the day. Yes, I used some road components inside of the dif element with the CSS class main component. These routes components can be placed anywhere inside off the router Broza rotor in this case and the associated component will be rendered in that place. Now the only thing I have to do is import all these components and their route component as well. And in the browser we can see the U I is updated. It shows the home component. However, look what happens when I go to the other route. By the fault, roads are inclusive. More than one drought component can match the Ural Path and render at the same time. But don't worry, we will fix this in the next lesson. 8. The Switch Component: in this lesson, I'm going to show you how to use the switch component to render only one route from the group of routes. The switch component works like a regular switch, a statement in JavaScript in order demo application. But the users and about Pat's contained this last character, so they are also much and render by the home route. This way we can display different components just by declaring that they belong to the same path. But in this case, this is not what we want. So we can use the exact property on the road for the home component to render it only if the Ural much is the path. Exactly. Now in the application, we can see that everything works fine. The routes users and about are not a match for the path of the home component anymore. Both only one component will be displayed at the time, so we can also use a switch component to render only the first route that matches the location. Even if you duplicate the about route, let me import this which component now if I visit the about page, its components will be rendered only ones. However, nothing's that just didn't need to specify the exact property for the homeopath or their wife users and about will also match it. And the con component will always be rendered because this is the first route that is defined on match, let me show you. The alternative, of course, is to define the comrade as the last one. There you have it. However, I leave the home route with the except properly. Now, you can also specify at the fourth round to render something when no path is much. This behaviour is implemented with a ready that component. You just need to pass the euro to ready recto with the two property. In fact, a switch component only accepts as Children either route or red erect elements wrote Elements are much using their path property while reiterate elements are much using their from property. Now, if I go to my home, the application will redirect me to the home. A right component that has no path, property or already read component that has no from property will always match the current location. That story, some quite this red erect at the end of the switch component can catch any path that was not previously match. Let's just say good bye before there you have it. Finally, something you need to be aware off is that the rhetoric component was navigate to a new location, replacing the curing want in the history stack just like a server side red erect does. 9. Route Render Properties: when you were under something with the route component. Three objects are passed as parameters much, which is an object that contains information about how the routes but much. The euro location, which is an immutable object that represents were The APP is now has properties to get the part. The Chorus String and the House of the Euro and History, An object for managing decision history in the browser with methods to go back and forward in the history stack. These properties are always passed no matter what render method you use in a component, you can get them from the properties object. The much object will be the one you'll be using more often, so you can destructor the properties object to get just that object. For example, this is how you will do it with a render function. By the way, there under function is useful when you want to pass custom properties to the component. You are going to render like the color property in this example, and this is how you do it using Children. Remember that the difference between render on Children is that the later always renders the element returned by the function this way, you can use the much property to know if the path actually matches the current Ural. If it doesn't, the much object will be empty. Okay, you can see this properties in action without modifying the application. Using the React Developer Tools Extension. For example, in Crumb, I'll open the developer stool and look for the react final. I'm going to expand all these notes and search for the home component. It's right here. If I selected, you'll see the three properties listed here. Here's the history object with some methods to control the browser says your history. Not is that history contains a location object, which is basically the same that the other location object the component is receiving as parameter. The only difference is that the location object in history is mutable, so it's not recommended to use something. We have the match object. If I navigate to their about page, you can see how its field with different data all right in the next lesson will use the much object to create a nested route 10. Nested Routes: Here's an example off a nester Drought Users is last details. Most of the time, they're two parts, the main path users, in this case on a soft path. Details. In this case, usually the soft part is defined as a part bearable. So in this case, often I d. It can take values like one or two. In fact, we're going to implement a nested route for or them a project just like these one. And for that, we're going to use the much property. Remember that much. It's an object that contains the following properties Barham and object with key value pairs parts from the Ural corresponding to the path by rebels, its exact on bullion with the value true if they your are much the bath pattern used in the road component and you're a a string that represents the magic portion of the URL. All right, so for the user section, we want to display a list off users, and each item off the list will be a link like it's Last Users is last one. It's last users last two, and so on that we show you the details of that user, so let's start by modifying the users component to generate links for some sample users. To keep things simple, I'm just going to the final function that good return a list. Another option will be to call on a B I to get the list off. Users in the company did update method and a store the least in the state of the component . So we need changes. It can be rendered. But I'm just going to the find an array. And with a four loop, I feel their ring with objects that just contain an I. D property that the represents the idea of the users on return. That least now I'm going to replace the body of the component and called the function. Then I used the math method. Remember that this method creates a new array with the results off a function called on every element in the ray. So this function is going to take a perimeter, that alcohol user that represents the object with the idea property I'm for every user. This component will render an H two element. Remember that would render in a leased off elements. React requires a key property with a unique value on every element. Then I'll have a wing component to create a link to show the details off that user. Finally, on import link on. If I run the application, we'll see the links are rendered correctly. Also, notice how the Ural changes going. I click on Sun Off This links. Now we can do something us to improve this. Instead of hard coding the users part off the path we can use them much of yet the component receives. If I opened the react developer store spinal, I look for the user component we can see The euro property has the value, its last users. So we can the instructor match from the properties object the component receives and use much dot yura instead of the hard core value is last, users this less and the beginning is important because otherwise we will be creating nested routes under the user spot. Great. The links are still working in. The next lesson will add the functionality to show the detail off each user 11. Using Route Parameters: All right, let's use their out parameters to show the details off each user. After the list off user links, I'm going to declare around component with a parameter to capture the user i d. These ideas are numbers so we can enforce the rule with a regular expression. Remember that bats accept any expression that the library, but to Rogic's can handle. I'm placing the rod component here because I want the user component to appear after the least. If you want this component to replace the user list, you'll have to place the least in app dot yes, next to the other route component. Anyway, if there's a match, the user component will be rendering. So I'm going to import the user and route components and create a new file. You said that gay? Yes, for this example, I'm just going to keep it simple on display. The idea of the user, but not is how the I D is extracted from the much the Baron's object using the same name that is defined in the bath. If you open the browser, you should see something similar to this. Now let's have other four message something like Please select a user from the least. But instead of creating a component for dismisses, I'll use the render property off the road component. Let's see, there you have it. Even if an embodied path is entered, the message is still appears. We can also go up these routes in a stretch component to guarantee that only one off the two is matched. Let me import the switch component and test their application. Great. It's working and we're done. But there's one last thing I want to mention. You have to be careful with the way you declare route. For example, if you declare the route that renders the missus first, the user component will never be rendered because the path like this last users this last one well, im much. The path is last users. So if you declare the route in this order that exact to avoid this behavior so we can say that the lesson here is always declared the most specific routes first. Now let's grow up up this glass 12. Final Thoughts: all right. By now, you should have a good understanding off what single paste applications are. How to create one with react and react. Rafter. You have learned that a route or keeps your application you y and the Ural you think and react. Router is the most popular rotor library for react. Also, you have learned how to set up React router, its most important component. How routes work on how to build Dynamic nest, the drought with part parameters for there's still a lot more to unearth. The official documentation covers some basic as well as more advanced interactive examples . Now in the class project, you'll bring all this together. You'll have to create a single place application with at least the following features. Home page, another patient with some text and not from page on a master detail page With Nestor Drought, the values can be Marco, for example, a catalogue off products or a list of messages. The app can be a bloated toe, coath, penn or coat sandbox so everyone else can check it out. Remember that you can find the complete source growth off the Dem A project on Get the Link is in the class description. And if you have questions or problems, leave a comment and I'll try to respond as soon as possible. All right, I hope you have enjoyed the class. I appreciate if you have the time to leave a review and if you like the class, follow me to be notified. When I release more classes, I'll see you next time taker and thanks for watching.