In this section, you’ll learn how to use react-router with urql to add some navigation to your app!
First add the required dependencies to the app. Open a terminal, navigate to your project directory and type:
Note: We are using
react-router-domdue to certain breaking changes in the later versions that are incompatible with this tutorial.
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
Link components that users can use to navigate between the
LinkList and the
Don’t get confused by the “other”
Linkcomponent that is used here. The one that you’re using in the
Headerhas nothing to do with the
Linkcomponent that you wrote before, they just happen to have the same name. This Link is exposed by the
react-router-dompackage and allows you to navigate between routes inside of your application.
Let’s set up some routes inside your
App component! We will create one route for the main
/, and one route for
You’ve now added the
/create routes to the app and added the
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
http://localhost:3000/create renders the
CreateLink component you just wrote in the previous section.
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:
LinkListwon’t display the newly created
Linkafter 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!