Hi Reactjs / Reactstrap Experts-
I am new to ReactJS and Reactstrap and I could not find a live example demonstrating NavItem switching via JS.
I am trying to get Reactstrap's Nav and Navlink toggle from one tab to another based on button clicks. In my code pen page below, when clicking "Go to Tab 2" when on Tab 1 results in a blank view and same happens when I click "Go to Tab 1" button in Tab 2. I am not sure where I could be going wrong.
Here is my JS code and a code pen created based on the below code.
Could you please help?
const { TabContent, TabPane, Nav, NavItem, NavLink, Card, Button, CardTitle, CardText } = Reactstrap;
class App extends React.PureComponent {
constructor() {
super();
this.state = {
activeTab: '1'
};
this.toggle = this.toggle.bind(this);
this.switchToTab1 = this.switchToTab1.bind(this);
this.switchToTab2 = this.switchToTab2.bind(this);
}
toggle(tab) {
if (this.state.activeTab !== tab) {
this.setState({
activeTab: tab
});
}
}
switchToTab2() {
this.toggle(2);
}
switchToTab1() {
this.toggle(1);
}
render() {
return (
<React.Fragment>
<Nav tabs className="card-header-tabs">
<NavItem>
<NavLink active={this.state.activeTab === '1'} onClick={() => { this.toggle('1'); }}>
Tab 1
</NavLink>
</NavItem>
<NavItem>
<NavLink active={this.state.activeTab === '2'} onClick={() => { this.toggle('2'); }}>
Tab 2
</NavLink>
</NavItem>
</Nav>
<div className="card-body">
<TabContent activeTab={this.state.activeTab}>
<TabPane tabId="1">
<h1>Content from Tab 1</h1>
<Button color="primary" onClick={this.switchToTab2}>Go to Tab 2</Button>
</TabPane>
<TabPane tabId="2">
<h1>Content from Tab 2</h1>
<Button color="primary" onClick={this.switchToTab1}>Go to Tab 1</Button>
</TabPane>
</TabContent>
</div>
</React.Fragment>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));