Search code examples
reactjsnavbar

how to redirect to an external link with menuItems/dropdownMenu navbar


What I'm trying to do is to redirect to an external link instead of an existing page on my website.

here is the code for Menu items:

export const MenuItems = [
  {
    title: 'Marketing',
    path: '/marketing',
    cName: 'dropdown-link'
  },
  {
    title: 'Consulting',
    href: '/consulting',
    cName: 'dropdown-link'
  },
];

Here is the code for drop down menu:

  const [click, setClick] = useState(false);

  const handleClick = () => setClick(!click);

  return (
    <>
      <ul
        onClick={handleClick}
        className={click ? 'dropdown-menu clicked' : 'dropdown-menu'}
      >
        {MenuItems.map((item, index) => {
          return (
            <li key={index}>
              <Link
                className={item.cName}
                to={item.path}
                onClick={() => setClick(false)}
              >
                {item.title}
              </Link>
            </li>
          );
        })}
      </ul>
    </>
  );
}

export default Dropdown;

Solution

  • Have a look here With Link component of react-router you can do that. In the "to" prop you can specify 3 types of data:

    a string: A string representation of the Link location, created by concatenating the location’s pathname, search, and hash properties. an object: An object that can have any of the following properties: pathname: A string representing the path to link to. search: A string representation of query parameters. hash: A hash to put in the URL, e.g. #a-hash. state: State to persist to the location. a function: A function to which current location is passed as an argument and which should return location representation as a string or as an object

    <Link to={{ pathname: "https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies" }} target="_blank" />