0

Example 1:

click on tab1. Tab 1 is active tab. Click again on tab1(tab1 is active tab) I don't want to call function start(). Click on tab 2 or tab 3 I want to call function start().

Example 2:

click on tab2. Tab 2 is active tab. Click again on tab2(tab 2 is active tab) I don't want to call function start(). Click on tab 1 or tab 3 I want to call function start().

Code here: https://codepen.io/kaka-milan/pen/YmXJJy?editors=1111

Drawing: https://imgur.com/ApsUxZo

var Tab = React.createClass({
  render: function() {
    return <li 
      className={ this.props.isActive ? 'navigation--active': '' }
      onClick={ this.props.onActiveTab }
    >
      <p>{ this.props.content }</p>
    </li>
  }
});

var Tabs = React.createClass({
  getInitialState: function() {
    return { selectedTabId: 1 }
  },

  isActive: function (id) {
    return this.state.selectedTabId === id;
  },

  setActiveTab: function (selectedTabId) {
    this.start();
    this.setState({ selectedTabId });
  },

  start: function() {
    return console.log('aaa')
  },

  render: function() {
    var total = this.props.data.points.total,
        tabs = total.map(function (el, i) {
          return <Tab 
            key={ i }
            content={ el.name } 
            isActive={ this.isActive(el.id) } 
            start= {this.start}
            onActiveTab={ this.setActiveTab.bind(this, el.id) }
          />
        }, this);

    return <ul className="navigation">
     { tabs }
    </ul>
  }
});

const data = {
  points: {
    total: [
      { id: 1, name: 'tab-1', text: 'text' },
      { id: 2, name: 'tab-2', text: 'text-2' },
      { id: 3, name: 'tab-3', text: 'text-2' }
    ]
  }
}

ReactDOM.render(
  <Tabs data={ data } />,
  document.getElementById('main')
);

2 Answers 2

1

You can add a condition to check whether the clicked tab is already selected or not, if it is already selected don't perform any operation else run it as normal

setActiveTab: function (selectedTabId) {
    if(!this.isActive(selectedTabId)){
     this.start();
     this.setState({ selectedTabId }); 
    }
  },

Demo

1

You just need to add condition to check its not equal with current state tab :

setActiveTab: function (selectedTabId) {
    if(this.state.selectedTabId!==selectedTabId){//ensure only trigger when different tab id
       this.start();
    this.setState({ selectedTabId });
    }

  },

Here is demo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.