score:0

You should use a function instead of an object to set new state. Cause of update of states is asynchronous and the value of state when you want change the state is not reliable. Change the add method like this:

add = targetKey => {
  let { activeKey } = this.state;
  if (targetKey !== activeKey){
    this.setState(prevState => { 
      const newState = {...prevState};
      newState.panes.push({title:'Tab 3', content:'Content of tab pane 3',key: activeKey+1});
      return newState;
    });
  }
};

Also change the remove method like this:

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/w71yLn24/


Related Query

More Query from same tag