DEV Community

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

Posted on • Edited on

5 1

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/c/TheWebSchool
Be the pioneer that follows me uh ? 😎

See you next time for some quick and polished tutorials !

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (1)

Collapse
 
thepassle profile image
Pascal Schilp
Comment hidden by post author

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