Ustariz Enzo
Posted on December 31, 2020
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);
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>
Then create that sweet function that changes the state :
const toggleTab = (index) => {
setToggleState(index);
}
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>
For each content :
<div
className={toggleState === 1 ? "content active-content" : "content"}
>
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 !
Posted on December 31, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 26, 2021