On closing a particular tab it closes all the tabs

Please look into this, on closing a particular tab it closes all the tabs that are open. I want only that particular tab to be closed.

remove = targetKey => {
  let { activeKey } = this.state;
  let lastIndex;
  this.setState(prevState => { 
      const newState = {...prevState};
      newState.forEach((pane, i) => {
          if (pane.key === targetKey) {
            lastIndex = i - 1;
          }
      });
      const panes = newState.filter(pane => pane.key !== targetKey);
      if (panes.length && activeKey === targetKey) {
          if (lastIndex >= 0) {
            activeKey = panes[lastIndex].key;
          } else {
            activeKey = panes[0].key;
          }
      }
      return ({panes, activeKey});
  });  
};

Check this link https://jsfiddle.net/yjumr4ox/1/

Upvotes: 2

Views: 88

Answers (1)

Saeed Shamloo
Saeed Shamloo

Reputation: 6554

The problem is because you are iterating over all the state at newState.forEach and newState.filter. You should iterate over panes in the state. like this:

remove = targetKey => {
let { activeKey } = this.state;
let lastIndex;
this.setState(prevState => { 
  const newState = {...prevState};
  newState.panes.forEach((pane, i) => {
      if (pane.key === targetKey) {
        lastIndex = i - 1;
      }
  });
  const panes = newState.panes.filter(pane => pane.key !== targetKey);
  if (panes.length && activeKey === targetKey) {
      if (lastIndex >= 0) {
        activeKey = panes[lastIndex].key;
      } else {
        activeKey = panes[0].key;
      }
  }
  return ({panes, activeKey});
});  
};

Upvotes: 1

Related Questions