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
v5
ofreact-router-dom
due 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 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 theHeader
has nothing to do with theLink
component that you wrote before, they just happen to have the same name. This Link is exposed by thereact-router-dom
package 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 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.
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 createdLink
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!