Routing

In this section, you’ll learn how to use the react-router library with Apollo to implement some navigation functionality!

Install dependencies

First add the required dependencies to the app. Open a terminal, navigate to your project directory and type:

Create a Header

Before moving on to configure the different routes for your application, you need to create a Header component that users can use to navigate between the different parts of your app.

This simply renders two Link components that users can use to navigate between the LinkList and the CreateLink components.

Don’t get confused by the “other” Link component that is used here. The one that you’re using in the Header has nothing to do with the Link component that you wrote before, they just happen to have the same name. This Link stems from the react-router-dom package and allows you to navigate between routes inside of your application.

Setup routes

You’ll configure the different routes for the app in the project’s root component: App.

For this code to work, you need to import the required dependencies of react-router-dom.

Now you need to wrap the App with BrowserRouter so that all child components of App will get access to the routing functionality.

That’s it. If you run the app again, you can now access two URLs. http://localhost:3000/ will render LinkList and http://localhost:3000/create renders the CreateLink component you just wrote in the previous section.

Implement navigation

To wrap up this section, you need to implement an automatic redirect from the CreateLink to LinkList after a mutation was performed.

After the mutation was performed, react-router-dom will now navigate back to the LinkList component that’s accessible on the root route: /.

Unlock the next chapter
What's the role of the Link component that you added in this chapter?
It renders a link that was posted by a user
It renders the input form for users to create new links
It lets you navigate to a different URL
It links your root component with all its children