简体   繁体   中英

local host getting added in prefix, when using NavLink in React router Dom for external link routing

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>

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>

编辑 local-host-getting-added-in-prefix-when-using-navlink-in-react-router-dom-for-e

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM