I am trying to input a link pointing to a subdomain into the navigation menu of a react theme. I am a bit embarrassed to ask the community for something that is most likely very simple. However, I've had a hard time finding any relatable examples on the web to help guide me. Below is the code and how I thought it would work, however it doesn't since it uses the current path ahead of the hyperlink.
#RouteName.ts
export enum RouteName {
Home = "/"
About = "/About"
Service = "/Service"
Portfolio = "https://sub.domain.com/"
Contact = "/Contact"
}
#Navigation.tsx
const ROUTES = [
{url: RouteName.Home, name: "Home"},
{url: RouteName.About, name: "About"},
{url: RouteName.Service, name: "Service"},
{url: RouteName.Portfolio, name: "Portfolio"},
{url: RouteName.Contact, name: "Contact"},
];
<Menu className="Menu">
{ROUTES.map((item) => (
<li key={item.url} className={pathname === item.url ? "active" : ""}>
<Link to={item.url}>{item.name}</Link>
</li>
))}
</Menu>
Result: localhost:3000/page-currently-on/https://sub.domain.com/
Need: https://sub.domain.com/
CodePudding user response:
Link
is a component from react Router and is meant for links inside your website. For external links, you can use a simple <a/>
tag
<a href="https://sub.domain.com/">Portfolio</a>
It would probably be better to create a route on /Portfolio
with a redirect like so:
<Route path='/Portfolio' component={() => {
window.location.href = 'https://sub.domain.com/';
return null;
}}/>
Then, you don't have to worry about it.
export enum RouteName {
Home = "/"
About = "/About"
Service = "/Service"
Portfolio = "/Portfolio"
Contact = "/Contact"
}
This solution creates makes the website easily expandable.
CodePudding user response:
You have to use pathname
when you want to link to the exact URL. In your case
<Link to={{pathname: item.url}} />
I know this doesn't play well with your types so have to trial and error a bit to implement it cleanly.
Source: https://thewebdev.info/2022/03/07/how-to-add-an-external-link-with-react-router/