hemoglobin
hemoglobin

Reputation: 841

Stop tabs from reloading after initial load in React

I have a React tabs layout that looks like this

Tab.js:

class Tab extends React.Component {
    constructor(props) {
        super(props);
        this.onTabClick = this.onTabClick.bind(this);
    }

    onTabClick() {
        this.props.handleTabClick(this.props.tabIndex);
    }
    render() {
        const { label, isActive, handleTabClick } = this.props;

        return (
            <li className="nav-item">
                <a className={this.props.isActive ? 'nav-link nav-active' : 'nav-link'}

                    onClick={this.onTabClick}
                >
                    {label}
                </a>
            </li>
        );
    }
}

TabHeader.js:

const TabsHeader = ({ activeTabIndex, data, handleTabClick }) => (
    <div>
      <ul className="nav nav-tabs border-0 align-self-center justify-content-between">
        {data.map(({ label }, index) => {
          const isActive = activeTabIndex === index;
          return (
            <Tab
              key={index}
              label={label}
              isActive={isActive}
              handleTabClick={handleTabClick}
              tabIndex={index}
            />
          );
        })}
      </ul>
    </div>
);

And I want to stop tabs content re-reloading every time a tab is clicked, but I'm not sure how I could accomplish this? Currently, it loads initially and then re-reloads every time you click on a tab. How can I fix this? Thanks!

Upvotes: 2

Views: 3449

Answers (1)

Yousaf
Yousaf

Reputation: 29282

You can use shouldComponentUpdate function inside react component. Tabs component won't re-render if this function returns false

shouldComponentUpdate(nextProps, nextState) {
  return this.state.value != nextState.value;
}

learn more about shouldComponentUpdate

Upvotes: 2

Related Questions