How to pass active state in React component to use within my tab/toggle buttons

Viewed 20

How to pass active state, when a button is clicked in below React component?

I have a component:

<MyLinks links={links}/>

Where I pass this array: const links: CopyType[] = ['link', 'embed'];

// MyLinks component:

const [copyLinkType, setCopyLinkType] = useState<CopyType>();

return (
    <React.Fragment>
      <ul>
        {links.map((linkType) => (
          <TabIcon
            type={linkType}
            onClick={() => {
              setCopyLinkType(linkType);
            }}
          />
        ))}
      </ul>
      {copyLinkType && <TabPanel type={copyLinkType} />}
    </React.Fragment>
  );

In the frontend you get 2 buttons which show/hide the <TabPanel /> with it's associated content.

How to get/pass an active state when a button is clicked?

I tried passing isActive state as a prop through <TabIcon isActive={isActive} /> and then on the onClick handler setIsActive(true); but this will pass active state to both buttons in the same time?

1 Answers

Try to use refs. Something like this (w/o typescript codepen):

const TabIcon = (props) => {
  const {activeRefs, onClick, type, index} = props
  return (
      <a onClick={()=>{
          // On each click change value to the opposite. Or add your 
          // logic here
          activeRefs.current[index] = !activeRefs.current[index]
          onClick()
        }}>
        {type}
      </a>
  )
}

const MyLinks = (props) => {
const [copyLinkType, setCopyLinkType] = React.useState();
// Array which holds clicked link state like activeRefs.current[index]
const activeRefs = React.useRef([]);
const links = ['link1', 'link2'];
  console.log({activeRefs})
return (
      <ul>
        {links.map((linkType, index) => (
          <TabIcon 
            index={index}
            activeRefs={activeRefs}
            type={linkType}
            onClick={() => {
              setCopyLinkType(linkType);
            }}
          />
        ))}
      </ul>
  );
}


ReactDOM.render(
  <MyLinks />,
  document.getElementById('root')
);
Related