Some Background
While creating this blog I ran into an issue where I wanted to direct my users to this blog from my website, but the default behavior of “Link” didn’t let me do that. An easy solution was to replace my “Link” tag with “a” tag, but since I was mapping my data to create multiple such cards I couldn’t make an exception for one or two situations. So I started searching the internet and after going through multiple articles with various solutions, I was finally able to achieve what I wanted. And since it took me pretty long to come to that solution I decided to share my solution here.
Problem
- Open the external link in a new tab.
- Need to direct user to an external link instead of a route within the react app.
SOLUTION
Opening link in a new tab:
Turns out this was pretty straightforward, “Link” accepts "target"
as a prop similar to the general “a” tag. So I just had to add: target='_blank'
and it did the trick.
Direct user to an external link:
This on the other hand wasn’t that straightforward. I spend quite some time before finding the solution (could easily be the fact that I am a noob in this field right now), but here is what I found. The "to"
prop of Link not only accepts strings, but it also accepts an object and one such key-value pair was the solution. Adding the desired URL to the key “pathname” did the job for me.
In my case, it was to={pathname: 'https://blog.preetparmar.com'}
As mentioned, I am still learning and this might be a pretty small thing to figure out but it took me a while to find this solution so just trying to help someone in the same boat as me. Feel free to reach out with any suggestions or a better solution.