Home > OS >  Select Current Tab Index In Map() Loop
Select Current Tab Index In Map() Loop

Time:08-22

I have the following:

const MyComp () => {
  const [activeTab, setActiveTab] = useState('1')
  const [data, setData] = useState(null)

  const handleTab = (e,tab,i) => {
    tab === 1 ? setActiveTab('2') : setActiveTab('1')
  }

  return(
  <div>
  {data !== null ?
  data.map( (v,i) =>
  <Card>
    <CardHeader> Message</CardHeader>
    <CardBody>
      <Nav> 
        <NavItem> 
          <Button className={activeTab === 1 ? 'active' : ''} onClick={(e) => handleTab(e,activeTab,i)} >
       {activeTab == 1 ? 'Reply' : 'Message'}
          </Button> 
        </NavItem> 
      </Nav>
      <TabContent activeTab={activeTab}>
        <TabPane tabId='1'> {v.message} </TabPane>
        <TabPane tabId='2'> {v.otherData} </TabPane> 
      </TabContent>
    </CardBody>
  </Card>)
: ""}
  </div>);
}

When I click one of the cards , all of them open to tab 2. I want just the specific cards to open its second pane and not all. I know it's something with the handler, but I'm not sure of the approach here, should I use the index in the pane? Which I've tried, nothing happens. Any suggestions to target the specific index?

CodePudding user response:

While updating a state property (activeTab) using its previous value the callback argument of the state setter should be used, since state updates may be asynchronous. Otherwise you may be using stale values.

 <Button onClick={handleButtonClick}>

 let handleButtonClick = (evt)=> {
     setActiveTab((tab)=> (tab==1 ? 2 : 1) );
 };

CodePudding user response:

Beware with your === and ==. Either:

  • keep numbers everywhere
  • keep strings everywhere
  • only use == (i.e. 1 === '1' // false but 1 == '1' // true)

I suspect this condition: tab === 1 to never be true and thus the tab never changing

  • Related