Reputation: 62
I am trying to route to an external link using the React Router Dom 6.4. But, the problem is the local host path is getting added. Can someone confirm, why?
localhost:3000/#/http://www.saveur.com/article/Recipes/
instead of
just: http://www.saveur.com/article/Recipes/
NavLink Code:
Getting the link through API
<div className='recipe-intro'>
<p className='cus-type'>{ Capitalize(recipieInfo.recipe.cuisineType[0])}</p>
<NavLink
target='_blank' to={{ pathname: `${recipieInfo.recipe.url}`}}
className="item-link">{recipieInfo.recipe.label}
</NavLink>
<NutriInfo recipieInfo = {recipieInfo} />
</div>
Routing:
Separate Component for Routes.
<div className="main-container for-routes">
<Routes>
<Route index path='/' element = {<LandingPage />} />
</Routes>
</div>
React Hashrouter:
Using Hashrouter from React router dom
<React.StrictMode>
<HashRouter>
<Level1Boundary>
<App />
</Level1Boundary>
</HashRouter>
</React.StrictMode>
Upvotes: 1
Views: 884
Reputation: 202608
The react-router-dom
NavLink
component doesn't handle external links; it's used only to navigate to pages your app is rendering routes for. If you want or need to link to an external resource then use a regular anchor (<a href>
) tag element.
If you want you can create a custom NavLink
component that tests if the passed to
prop is a valid external URL and conditionally render an anchor <a>
tag or the RRD NavLink
component. In the following example I've used the is-url to validate a URL string.
Example:
import { NavLink as BaseNavLink } from "react-router-dom";
import isURL from "is-url";
const NavLink = ({ children, to, ...props }) => {
return isURL(to) ? (
<a href={to} {...props}>
{children}
</a>
) : (
<BaseNavLink to={to} {...props}>
{children}
</BaseNavLink>
);
};
<NavLink to="/test">Test</NavLink>
<NavLink to="http://www.saveur.com/article/Recipes/">External Test</NavLink>
Upvotes: 1