alo gon
alo gon

Reputation: 187

Switching between controlled mode (by using `selectedIndex`) and uncontrolled mode is not supported in `Tabs`

I'm trying to implement some tabs using react-tabs in my next/react application.

I have the main page project/:id, that always opens in the 0 index tab, and when selecting each tab, the tab name is added to the route, example: project/:id/one-tab.

This way, if I share the link project/:id/two-tab, the site opens in the 1 index tab.

But I'm getting the error

react-dom.development.js:20312 Uncaught Error: Switching between controlled mode (by usingselectedIndex) and uncontrolled mode is not supported inTabs. at Function.copyPropsToState (Tabs.js:65) at getDerivedStateFromProps (Tabs.js:50)

My component looks like this

   class Project extends React.Component {

       constructor(props) {

          super(props);
          resetIdCounter();

       }

   state = {
     tabIndex: null
   };

   static async getInitialProps({ query }) {
      return { query };
   }

 render() {
    const { query } = this.props;
    const { tabIndex } = this.state;

    const TAB = {
      tab1: 0,
      tab2: 1,
    };

     return (

            <div>
              <Tabs
                selectedIndex={tabIndex || TAB[query.tab]}
                onSelect={index => this.setState({ tabIndex: index })}
              >
                <StyledTabList>
                  <StyledTab
                    onClick={() =>
                      Router.replaceRoute("one-tab", { id })
                    }
                  >
                    One tab
                  </StyledTab>
                  <StyledTab
                    onClick={() => Router.replaceRoute("two-tab", { id })}
                  >
                    Two tab
                  </StyledTab>    
                </StyledTabList>
              </Tabs>
            </div>
      );

   }
 }

 export default Project;

Upvotes: 1

Views: 1434

Answers (1)

sklepowich
sklepowich

Reputation: 31

I ran into this same error while using this library. I was able to resolve it by making sure that the value passed to the selectedIndex prop was defined (not undefined or null) before the return function.

So change this :

const TAB = {
      tab1: 0,
      tab2: 1,
    };

return (
            <div>
              <Tabs
                selectedIndex={tabIndex || TAB[query.tab]}
                onSelect={index => this.setState({ tabIndex: index })}
              >

Into this :

const TAB = {
      tab1: 0,
      tab2: 1,
    };
const selectedIdx = tabIndex ? tabIndex : TAB[query.tab]
return (
            <div>
              <Tabs
                selectedIndex={selectedIdx}
                onSelect={index => this.setState({ tabIndex: index })}
              >

EDIT: You could also just set the state.tabIndex = 0 in your constructor, since your 0 index tab is your default tab.

Upvotes: 3

Related Questions