A Simple Way to Render Tabs/Navigation in React!

rizz0s profile image Summer Rizzo ・2 min read


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):

│   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');

      {/* this is the main content of the page */}

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}) {

      <div onClick={() => setSelectedTab('about')}>About</div>
      <div onClick={() => setSelectedTab('product')}>Product</div>
      <div onClick={() => setSelectedTab('contact')}>Contact</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!

Posted on May 27 by:

rizz0s profile

Summer Rizzo


Freshly baked programmer and general blob. Recent graduate of Software Engineering at Flatiron School in Brooklyn, NY.


markdown guide

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