Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set active tab in Tab from Material UI programatically

Tags:

I'm using Material UI and React, I'm creating multiple tabs programatically as can be seen below:

return (
    <div>
        <Tabs>
            {this.state.elements.map(elem => {
                return (
                    <Tab key={elem.elemID} label={elem.name} >
                        <div>
                           // rest removed for brevity
                        </div>
                    </Tab>
                )
            })}
        </Tabs>
    </div>
);

This works, and the tabs are displayed, but the problem is that by default, when the component renders, the first tab is the active one. Whereas, I want to set the active tab programatically based on an id value that I get from props. So basically, if this.props.selectedID === elem.elemID then I want that tab be the active tab when the component renders. Of course, once the component is rendered, the user should be free to click and switch between tabs. Any idea how to achieve it?

like image 666
typos Avatar asked Aug 31 '17 10:08

typos


1 Answers

Use the value prop on Tabs and Tab to make this a controlled component:

<Tabs value={this.props.selectedID}>
    {this.state.elements.map(elem => {
            return (
                <Tab key={elem.elemID} label={elem.name} value={elem.elemID}>
                    <div>
                       // rest removed for brevity
                    </div>
                </Tab>
            )
        })}
</Tabs>
like image 108
thedude Avatar answered Oct 12 '22 02:10

thedude