beingalex
beingalex

Reputation: 2476

React Tabs and selectedIndex

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>

Upvotes: 4

Views: 11319

Answers (2)

Karthik
Karthik

Reputation: 61

As per your above comments you need to save with parent and child components values..

so you can use state and constructors is very effective..

No need to send parameters to parent . you can access the state value from the parent .

Upvotes: 0

Just code
Just code

Reputation: 13801

 <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.

Upvotes: 2

Related Questions