DEV Community

Cover image for Create (lovely) React Tabs !
Ustariz Enzo
Ustariz Enzo

Posted on • Updated on

Create (lovely) React Tabs !

No ! You don't need some dependencies to create your own Tabs with React in 2 minutes.

(Full Source code at the bottom)


If you prefer to watch the video version it's right here :

1. Setup your state

Import useState, and make it start at "1", since we want the first tab to show off.

const [toggleState, setToggleState] = useState(1);
Enter fullscreen mode Exit fullscreen mode

2. Setup the toggle

In the JSX, setup an eventListener, notice that we use an anonymous function to call a function with an argument :

<button
   className="tabs"
   onClick={() => toggleTab(1)}
>
  Tab 1
</button>

Enter fullscreen mode Exit fullscreen mode

Then create that sweet function that changes the state :

const toggleTab = (index) => {
    setToggleState(index);
}
Enter fullscreen mode Exit fullscreen mode

Wow, the logic is already done !

3. It's conditionnal class rendering time.

Now we want to display the right tab & the right content at the same time, we will indeed use the handy ternary operator.

For each tab :

 <button
    className={toggleState === 1 ? "tabs active-tabs" : "tabs"}
    onClick={() => toggleTab(1)}
 >
    Tab 1
 </button>
Enter fullscreen mode Exit fullscreen mode

For each content :

<div
className={toggleState === 1 ? "content  active-content" : "content"}
>
Enter fullscreen mode Exit fullscreen mode

And voilà ! 🥖🍷
A lovely reusable component.

Source code, with all the shiny CSS is right here :
https://github.com/Ziratsu/YT-REACT-TABS/blob/master/src/App.js

Come and take a look at my brand new Youtube channel :
https://www.youtube.com/channel/UCiukrDWz1wqlHAvIdqgqmQg
Be the pioneer that follows me uh ? 😎

See you next time for some quick and polished tutorials !

Discussion (1)

Collapse
thepassle profile image
Info Comment hidden by post author - thread only accessible via permalink
Pascal Schilp

You should really consider making this accessible instead. Currently users that rely on keyboard navigation wont be able to use your tabs component. Not making components accessible excludes users from your apps, and this effect only gets amplified by sharing inaccessible component tutorials like these; other beginning developers may see this post and learn bad habits/inaccessible components.

You can find more information on making accessible tabs here: w3.org/TR/wai-aria-practices-1.1/e...

Some comments have been hidden by the post's author - find out more