Do not understand why duplicate data is being copied into my url in react component Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Do not understand why duplicate data is being copied into my url in react component without wasting too much if your time.

The question is published on by Tutorial Guruji team.

In my App.js (or main component) I am rendering my Navbar component

import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import Navbar from './components/layout/navbar/Navbar';

import './App.css';

const App = () => {
  return (
    <Router>
      <Navbar />
    </Router>
  );
};

export default App;

In my Navbar I am rendering my NavLinks component and passing in as props the menu

import React from 'react';
import NavLinks from './NavLinks';

const menu = [
  { id: 1, label: 'Home', url: 'https://www.google.com/?client=safari' },
  { id: 2, label: 'Contact us', url: 'https://stackoverflow.com' },
];

const Navbar = () => {
  return (
    <nav>
      <NavLinks items={menu} />
    </nav>
  );
};

export default Navbar;

In my NavLinks I bring in as props the items which is the menu we saw before and map through it and pass in as props url and label.

import React from 'react';
import NavLink from './NavLink';

const NavLinks = ({ items }) => {
  const links = items.map((item) => (
    <NavLink key={item.id} url={item.url} label={item.label} />
  ));

  return <ul>{links}</ul>;
};

export default NavLinks;

In my NavLink component I am creating a Link to the url

import React from 'react';
import { Link } from 'react-router-dom';

const NavLink = ({ url, label }) => {
  return (
    <li className='nav-item'>
      <Link to={url}>{label}</Link>
    </li>
  );
};

export default NavLink;

For some reason my Link has a path of multiple google urls. The url to the google homepage is duplicated many times. I do not know why this is happening.

Answer

Link component is to Provides declarative, accessible navigation around your application

If you use the Link component for the external URL, this will keep appending your URL to the previous ones.

For navigating to an external URL, I would suggest you to use native HTML tag instead:

const NavLink = ({ url, label }) => {
  return (
    <li className="nav-item">
      <a href={url}>{label}</a>
    </li>
  );
};

Working example:

Edit elastic-borg-kfbvv

We are here to answer your question about Do not understand why duplicate data is being copied into my url in react component - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji