DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Programmatic Brand Extraction: Pulling Logos, Colors, and Assets from Any URL
  • The Death of the CSS Selector: Architecting Resilient, AI-Powered Web Scrapers
  • A Guide to Parallax and Scroll-Based Animations
  • Building a Card Layout Using CSS Subgrid

Trending

  • The Context Window Trap: Why More Context Doesn’t Mean Better AI
  • Nobody Designs an RBAC Mess; Everyone Ends Up With One
  • Beyond @Transactional: Solving the Dual-Write Problem in Distributed Microservices
  • The Twelve-Factor Agents: Building Production-Ready LLM Applications

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Languages
  4. Create a Svelte Reusable Tab Component Without Complicated CSS

Create a Svelte Reusable Tab Component Without Complicated CSS

Learn how to create a reusable tab component in Svelte without complicated CSS.

By 
Saurabh Dashora
DZone Core CORE ·
Mar. 03, 22 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
10.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Tabs are a key feature in any application. They are needed for effective navigation between the various parts of the application and switching between different views. We can easily create and manage tabs in Svelte. However, the question is whether we can create a Svelte Reusable Tab Component.

We can definitely create a reusable tab component in Svelte very easily. All we have to use is basic Javascript logic, some rudimentary CSS, and a custom event dispatcher. We don’t need to use complicated routing solutions. By simply using these basic building blocks, we can create a working tab solution that also keeps track of the active tab. Such an approach is very suitable for small applications.

In this post, we will look at the various steps involved in creating this reusable component with code snippets.

Why Reusable Tabs?

The functionality of tabs is pretty simple. It provides an option for users to switch between different views such as Home and About pages. These views could be at the application level like a navigation bar at the top of a website. It could also be on a component level where we have multiple sections within a component.

Reusable tabs help us build once and use many times.

We can build a basic reusable tab component with some customization options. The advantage of the reusable tab component is to avoid repetitive logic. Also, we can easily maintain similar styles across all the tabs within our application. This provides our application with a coherent design approach.

Create Reusable Tab Component

Let us first create a reusable tab component as below:

JavaScript
 
Tab.svelte<script>
    import { createEventDispatcher } from 'svelte';
    const dispatch = createEventDispatcher();

    export let tabItems;
    export let activeItem;

</script>

<div class="tabs">
    <ul>
        {#each tabItems as item}
            <li on:click={() => dispatch('tabChange', item)}>
                <div class:active={item===activeItem}>{item}</div>
            </li>
        {/each}
    </ul>
</div>

<style>
    .tabs {
        margin-bottom: 40px
    }
    ul {
        display: flex;
        justify-content: center;
        padding: 0;
        list-style-type: none;
    }
    li {
        margin: 0 16px;
        font-size: 18px;
        color: #555;
        cursor: pointer;
    }
    .active {
        color: #d91b42;
        border-bottom: 2px solid #d91b42;
        padding-bottom: 8px;
    }

</style>

This component requires two inputs. One is the list of tab options. The second is the currently active item. Using each block in Svelte, the tab options are rendered.

We also apply a special CSS class to the tab option when it is currently an active item. Lastly, we use the Svelte custom event dispatcher to dispatch an event in case the user changes the active tab option. Basically, this makes sure that the active class is applied to the correct option.

Using the Reusable Tab Component

We can now use the tab component in another component.

See the below example:

JavaScript
 
App.svelte<script>
    import Tabs from './shared/Tabs.svelte'

    let tabItems = ['Home', 'Books', 'About']
    let activeItem = 'Home'

    const triggerTabChange = (event) => {
        activeItem = event.detail;
    }
    
</script>

<main>
    <Tabs tabItems = {tabItems} activeItem = {activeItem} on:tabChange={triggerTabChange} />
    {#if activeItem === 'Home'}
       <p>Welcome to the Library Management System</p>
    {:else if activeItem === 'Books'}
       <p>List of available books</p>
    {:else}
       <p>This is a demo project to show the capabilities of Svelte</p>
    {/if}
</main>

<style>
    main {
        max-width: 960px;
        margin: 40px auto
    }
</style>

Here, we create an array tabItems. Basically, this array contains the items for the tab component. Also, we have the activeItem that is initially hard-coded to Home.

While using the Tabs component, we pass tabItems and activeItem as props. Also, we handle the tabChange event and modify the activeItem accordingly. This is done using the triggerTabChange() function. We also have some basic logic using Svelte conditional blocks to show different text for different tab options selected by the users.

See the below screenshot where we can see the tab options rendered along with special styling for the currently active option.

Rendered Tab

Conclusion

Svelte is great for building reusable components. The Reusable Tab is one of the examples of the same. If you have any comments or queries about this post, please feel free to mention them in the comments section below.

CSS Svelte

Published at DZone with permission of Saurabh Dashora. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Programmatic Brand Extraction: Pulling Logos, Colors, and Assets from Any URL
  • The Death of the CSS Selector: Architecting Resilient, AI-Powered Web Scrapers
  • A Guide to Parallax and Scroll-Based Animations
  • Building a Card Layout Using CSS Subgrid

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook