Search code examples
javascriptreactjssemantic-ui-react

Tabs not loading pane information


I’m having a problem with Tabs in semantic-ui-react, I’m trying to use a vertical tab like shown here

https://react.semantic-ui.com/modules/tab#tab-example-vertical-true

The code used in the example is this:

import React from 'react'
import { Tab } from 'semantic-ui-react'

const panes = [
  { menuItem: 'Tab 1', render: () => <Tab.Pane>Tab 1 Content</Tab.Pane> },
  { menuItem: 'Tab 2', render: () => <Tab.Pane>Tab 2 Content</Tab.Pane> },
  { menuItem: 'Tab 3', render: () => <Tab.Pane>Tab 3 Content</Tab.Pane> },
]

const TabExampleVerticalTrue = () => (
  <Tab menu={{ fluid: true, vertical: true, tabular: 'right' }} panes={panes} />
)

export default TabExampleVerticalTrue

Using this code as shown above works as it should, i.e when I click on a tab it loads the information for the tab in the tab pane.

In my render function I have

<Tab menu={{ fluid: true, vertical: true, tabular: 'right' }} panes={panes} />

When I try to replace the panes provided with my code below it doesn’t change the tab when clicked, it shows the new tab is clicked but doesn't load the new tab pane.

const panes = [];
for(var i = 0 ; i < 2 ; i++) {
  panes.push({ menuItem: (i+1).toString(), key:{i}, render: () =>(<Tab.Pane>{i}</Tab.Pane>) })
};

Thanks

EDIT: I think it is changing the tab but when rendering I think the i value in the tab pane is rendering the value at the end of the for loop and not setting the value as what i is inside the for loop for each iteration


Solution

  • The problem is that you have a loop that creates closures (the render functions), which refer to the var-declared loop variable i. After the loop, all render functions refer to the same i, which will now have value 2. You can fix it by changing var to let, which causes the i in each loop iteration to have its own scope. Alternatively, you can use a map instead of a loop:

    const panes = new Array(2).fill().map((__, i) => (
      { menuItem: ''+(i+1), key:{i}, render: () => <Tab.Pane>{i+1}</Tab.Pane> }
    ));