DEV Community

Summer Rizzo
Summer Rizzo

Posted on

A Simple Way to Render Tabs/Navigation in React!

Hi!

So, I've used this method in a few web apps so far and I've found it to be very straight-forward and easy to implement, esp. considering that no libraries are needed. Just core React concepts!

The general idea is to use an object with the keys pointing to whichever component you want to render. The key will be held in the parents' state.

Let's say you have a file structure that looks like this (emitting the React boilerplate structure and looking only at src):

src
│   app.jsx
│   index.html
│   index.js    
│
└─── components
   │   navbar.jsx
   │   about.jsx
   │   product.jsx
   │   contact.jsx

In this case, app.jsx will be in charge of rendering the overall structure of the page (the parent). It will look something like this (excluding imports and using React hooks):

const TABS = {
  'about': <About />,
  'product': <Product />,
  'contact': <Contact />
}

export default function App () {

  const [selectedTab, setSelectedTab] = useState('about');

  return(
    <div>
      <NavBar 
        setSelectedTab={setSelectedTab}
      />
      {/* this is the main content of the page */}
      {TABS[selectedTab]}
    </div>
  )
}

So, the selected tab in state will determine which component is rendered to the page. The setState function is passed down as a prop to the navigation bar, which will set the state appropriately when a user clicks on a tab.

Here's what NavBar might look like (simplified, of course):

export default function NavBar ({setSelectedTab}) {

  return(
    <div>
      <div onClick={() => setSelectedTab('about')}>About</div>
      <div onClick={() => setSelectedTab('product')}>Product</div>
      <div onClick={() => setSelectedTab('contact')}>Contact</div>
    </div>
  )
}

And that's pretty much all there is to it! Obviously, it may get more complicated depending on the complexity of your website, but the basic idea should remain the same.

With <3, happy coding!

Top comments (1)

Collapse
 
isajal07 profile image
Sajal Shrestha

This such a simple and smooth approach. Thanks for this. 👏🏼