raa89
raa89

Reputation: 25

React - Link to doesn't always work as expected

I am building a Pinterest clone that uses React on the front-end.

The home page is /pins, which is just an index of all the pins. In the Pin Index Item component, when a user clicks on the pin, I am using Link to go to the correct path.

Here is the Link to in the PinIndexItem.jsx

<Link to={`users/${pin.author_id}/boards/${pin.board_id}/pins/${pin.id}`}>

Here is the Route in my App.jsx

<Switch>
 <ProtectedRoute exact path='/users/:userId/boards/:boardId/pins/:pinId' component={PinShowContainer} />
</Switch>


When I go from the pins route, which is

#/pins/

It works just fine

However, I am on a user's pin board, which is

users/${pin.author_id}/boards/${pin.board_id}/

instead of going to

users/${pin.author_id}/boards/${pin.board_id}/pins/${pin.id}

, it adds onto the path:

users/${pin.author_id}/boards/users/${pin.author_id}/boards/${pin.board_id}/pins/${pin.id}`

I am confused why it works differently in the second case. Thank you.

Should I just use history.push in both cases?

Upvotes: 0

Views: 198

Answers (1)

Florian Motteau
Florian Motteau

Reputation: 3714

On a link element, if you omit the initial / on the href attribute (the target URL for the link), the href attribute value will be appended to the current URL. This is a link relative to the current page (href value will be appended to the current page full URL).

For example if the current page URL is /here and you set up a link with href="there", then clicking on that link will get you to /here/there.

If you want to set up a link to an absolute path, you need to add an initial / on the href attribute. From my previous example, if the current page URL is /here and you set up a link with href="/there", then clicking on that link will get you to /there.

You should be able to solve your problem by switching to absolute paths, or use different relative paths.

See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a for a complete doc.

Upvotes: 1

Related Questions