In this section, you’ll learn how to use react-router with urql to add some navigation to your app!

Install dependencies

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

Note: We are using v5 of react-router-dom due to certain breaking changes in the later versions that are incompatible with this tutorial.

Create a Header

Before you’ll 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 of react-router-dom’s 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 is exposed by the react-router-dom package and allows you to navigate between routes inside of your application.

Setup routes

Let’s set up some routes inside your App component! We will create one route for the main LinkList at /, and one route for CreateLink at /create.

You’ve now added the / and /create routes to the app and added the Header.

Now you’ll need to add an additional Provider component around your app for react-router-dom to work properly.

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.

Run the app and access it at localhost:3000

Add automatic redirects

To wrap up this section, let’s also add an automatic redirect to the CreateLink component. To do that you can use the history prop that react-router passes down to all components that are wrapped in a route.

We want to use the history.push method to redirect to the LinkList route once the mutation has completed. We can do this by using the promise that executeMutation returns when it’s being called.

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

Note: The LinkList won’t display the newly created Link after the app redirects to it. For now you can simply refresh to see the changes made. You’ll learn how to update the data after the mutation is being triggered in a future chapter!

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