0

There is a Tab component with multiple tabs, it is needed that when one of those tabs is clicked to open a link in a new tab in browser.

This is the code:

import { LocationDescriptor } from 'history';
import React, { AnchorHTMLAttributes } from 'react';
import { NavLink } from 'react-router-dom';

export interface ITabLinkItem extends AnchorHTMLAttributes<HTMLAnchorElement> {
  link: LocationDescriptor;
  name: string;
  disabled?: boolean;
}

export interface TabLinkProps {
  tabs: Array<ITabLinkItem>;
}

export function TabsLink({ tabs }: TabLinkProps) {
  const preventClick = (event: React.MouseEvent, disabled = false) => {
    disabled && event.preventDefault();
  };

  const clickTab = (event: React.MouseEvent, tab: ITabLinkItem) => {
    preventClick(event, tab.disabled);
    const { link } = tab;

    if (link === '/test') {
      // OPEN IN NEW TAB
    }
  };
  return (
    <div>
      {tabs.map((tab: ITabLinkItem, index: number) =>
        <NavLink
          key={index}
          to={tab.link}
          onClick={(event: React.MouseEvent) => clickTab(event, tab)}
        >
          {tab.name}
        </NavLink>
      )}
    </div>
  );
}

export default TabsLink;

Is it a way to trigger that tab opening when the condition is true?

Leo Messi
  • 5,157
  • 14
  • 63
  • 125
  • 2
    you can use this `window.open(url)` to open in new tab – Usama Jun 09 '22 at 11:04
  • @Usama it seems to work but is it a way to open that tab without navigating to it, and remain on the current one? – Leo Messi Jun 09 '22 at 11:12
  • I searched about this but didn't find any workaround. You can check this [link](https://stackoverflow.com/questions/20278498/open-a-new-tab-with-javascript-but-stay-on-current-tab-using-javascript) – Usama Jun 09 '22 at 11:25

1 Answers1

0

You cannot maintain state in a new tab (so you will have to use cookies/localstate or some nifty database connections etc if you want that). So if this is the case and the new tab may be 'dumb' then why not use an a link with a target='_blank'.

  • Instead of triggering a click event programatically on a link with a target blank, why not just use window.open as the first comment suggests? – Dimitar Jun 09 '22 at 11:17