Reputation: 324
Is there a way I could shorten this using spread operators so I am not having to call the createtab function over and over. Especially in cases where I have a much bigger and deeper navigation bar?
import React from "react";
function createTab(page, props) {
return (<li className="nav-item">
<a href={"#" + page} onClick={() => props.handlePageChange(page)} className={"nav-link" + (props.currentPage === page? " active" : "")}>
{page}
</a>
</li>)
};
function NavTabs(props) {
return (
<ul className="nav nav-tabs">
{createTab("Home", props)}
{createTab("About", props)}
{createTab("Blog", props)}
{createTab("Contact", props)}
</ul>
);
};
export default NavTabs;
Upvotes: 2
Views: 63
Reputation: 33994
You can send all the pages in array to createTab
function NavTabs(props) {
return (
<ul className="nav nav-tabs">
{createTab(["Home", "About","Blog","Contact"] , props)}
</ul>
);
};
And here in createTab function use pages array and render li elements
function createTab(pages, props) {
return pages.map((page, index) => (
<li key={"Key-"+index} className="nav-item">
<a href={"#" + page} onClick={() => props.handlePageChange(page)} className={"nav-link" + (props.currentPage === page? " active" : "")}>
{page}
</a>
</li>))
};
Upvotes: 2
Reputation: 4333
You can do something like ["Home","About","Blog"].map(tab => createTab(tab, props))
return (
<ul className="nav nav-tabs">
{["Home","About","Blog"].map(tab => createTab(tab, props))}
</ul>
)
Upvotes: 0
Reputation: 4126
You can just put your "tabs" in an array, then call map
to create components out of them
function NavTabs(props) {
const tabs = ['Home', 'About', 'Blog', 'Contact'];
return (
<ul className="nav nav-tabs">
{tabs.map(t => createTab(t, props))}
</ul>
);
};
Upvotes: 0