Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    React Router: Router, Route, and Link

    0.14 - 16
    react-routerReact Router

    In this lesson we'll take our first look at the most common components available to us in react-router; Router, Route, and Link.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    To get started with React Router, we're going to import React, and we're also going to import the React Router library.

    From React Router, we're going to bring in Router, Route, Link, and HashHistory. We're going to go and create a handful of components here that represent the pages within a route application. This one's going to be home, going to return a div with an H1 that says home. The next one will be about and the last one will be contact.

    We're going to go and set up our outer component here. We're just going to call that app. It's going to return our router component, which we set up with a router component tag. It takes in a history. This could be HashHistory or browser history, and we'll talk more about that later. For right now, we're going to be using the HashHistory.

    We can set up our individual routes with a route component. A route component takes in a path, and it also takes in the component that should be presented at that path. This will be our route path that renders a home component. Set up another one of these at the about path, and present the about component. Finally, we'll have /contact that presents the contact component.

    Let's go and export that by default, save it, and on the right you can see we're at our route path. This path right here is represented by the HashHistory path. We can go ahead and change that HashHistory path to contact, and we'll be at our contact component. We could change it to about, and now we're at our about component.

    We're not actually outputting anything that we can click on and navigate with, and that's where the link component comes into play. We're going to go ahead and create a new component here called links. Here, we're going to return a simple nav component, and a handful of link components.

    The link component operates exactly like an anchor tag, except instead of an href, you're going to get a to prop. Here, we're going to say to/ and then we're going to have a text or innerHTML there of home. This one will say "about" and "about." We'll do one more that'll be /contact and we'll say "contact" inside of that.

    What we're going to do is render our links component inside of each one of these page components. So links, close that, save it. We've got our actual link. If we click on home, we get home, about, we get about, and contact, we get contact.