Reputation: 51
How to add a tab Dynamically on button click
i have tried all examples but none of them helped me
For example :- below intially 2 bootstrap tabs are there Named Tab1 and Tab2 .. Add Tab button is there. When we click on that automatically tab3 needs to bind How to do this guyz give me suggetions please
Reference Link :- https://www.bootply.com/61679
Upvotes: 3
Views: 7122
Reputation: 15698
I suppose this would be the basic template you need to accomplish this feature in React.
See this sandbox here: https://codesandbox.io/s/romantic-wiles-w2uwh
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
state = {
tabs: [
{ name: "Tab 1", content: "Wow this is tab 1" },
{ name: "Tab 2", content: "Look at me, it's Tab 2" }
],
currentTab: { name: "Tab 1", content: "Wow this is tab 1" }
};
createTabs = () => {
const { tabs, currentTab } = this.state;
const allTabs = tabs.map(tab => {
return (
<li>
<button
className={currentTab.name == tab.name ? "tab active" : "tab"}
onClick={() => this.handleSelectTab(tab)}
>
{tab.name}
</button>
</li>
);
});
return <ul className="nav nav-tabs">{allTabs}</ul>;
};
handleSelectTab = tab => {
this.setState({
currentTab: tab
});
};
handleAddTab = () => {
const { tabs } = this.state;
const newTabObject = {
name: `Tab ${tabs.length + 1}`,
content: `This is Tab ${tabs.length + 1}`
};
this.setState({
tabs: [...tabs, newTabObject],
currentTab: newTabObject
});
};
render() {
const { currentTab } = this.state;
return (
<div className="container">
<div className="well">
<button className="add-tab-button" onClick={this.handleAddTab}>
<i className="text-primary fas fa-plus-square" /> Add Tab
</button>
{this.createTabs()}
<div className="tab-content">{currentTab.content}</div>
</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Upvotes: 5