Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Tabs and selectedIndex

Tags:

reactjs

I'm using React Tabs (https://github.com/reactjs/react-tabs) in controlled mode.

Setting the tabIndex in a parent Component:

this.setState({
    tabIndex: 1,
});

And passing the tabIndex through in the properties:

<TabContents tabIndex={this.state.tabIndex} />

Putting the component into "controlled mode":

export default class TabContents extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            tabIndex: 0
        }

    }

    ...

    render() {

        <Tabs selectedIndex={this.props.tabIndex} onSelect={tabIndex => this.setState({ tabIndex })}>

    ...

    }
}

This works and the second tab (with a tabIndex of 1) is selected.

However when I click on any other tab, nothing happens. It's stuck on the tabIndex of 1. How do I go about allowing to switch tabs when in "controlled mode"?

Full JSX:

<Tabs selectedIndex={this.props.tabIndex} onSelect={tabIndex => this.setState({ tabIndex })}>
    <TabList>
        <Tab>Accounts <span className="badge badge-pill badge-primary">{this.props.selectedSource ? this.props.sources[sourceIndex].accounts.length : 0}</span></Tab>
        <Tab>Forms</Tab>
    </TabList>

    <TabPanel>
        {this.props.activeDetails ? this.props.activeDetails.make : null }

        {accounts && (
            <ul className="accounts-list list-group">{accounts}</ul>
        )}

        {disabled_accounts && (
            <ul className="accounts-list disabled list-group">{disabled_accounts}</ul>
        )}

    </TabPanel>
    <TabPanel>
        <h2>Forms</h2>
        {this.props.activeDetails ? this.props.activeDetails.make : null }
    </TabPanel>
</Tabs>
like image 685
beingalex Avatar asked Oct 23 '25 04:10

beingalex


1 Answers

 <Tabs selectedIndex={this.props.tabIndex} onSelect={tabIndex => this.setState({ tabIndex })}>

As per your question you have multiple child components, But on select you are changing the local state onSelect={tabIndex => this.setState({ tabIndex })}

What you need to do?

  1. You need to create one method in parent component
  2. Pass that props to children components
  3. on children onSelect call that parent method

Now, parent will be responsible for active tab.

Here is an example of calling parent from child.

like image 186
Just code Avatar answered Oct 24 '25 17:10

Just code



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!