isak.me - a blog by isak solheim

Bi-weekly updates about things that interest me, things I have built and things I have learned.

How To Use Relative Links With React Router

In this tutorial, I’ll show you how to create a relative link with React Router. We will be writing the component EditButton which renders a button that appends /edit to the path the user is on. This will allow us to reuse the component all over our React project.

import React from "react";
import { Link } from "react-router-dom";

const EditButton = () => (
  <Link to={´${window.location.pathname}/edit´}>
    <button>Edit</button>
  </Link>
);

export default EditButton;

We start by writing the functional component EditButton. It has a button element wrapped around by the Link component from React Router.

The link path is created by using window.location.pathname, which returns an initial '/' followed by the path of the URL as a string. Lastly, we add our /edit path.

The resulting link looks like this: ´${window.location.pathname}/edit

And there we have it. I hope you have found this useful.