DEV Community

Cover image for Create toggle with tailwind and alpinejs
Rishiraj Purohit
Rishiraj Purohit

Posted on

Create toggle with tailwind and alpinejs

I know this is pretty dry read, but it's here in case someone or future me does a google search.

If you have any question please let me know in comments

<!-- Role -->
<div class="my-4 mx-auto">
    <h2 class="text-xl font-bold text-gray-700 text-center w-full w-full text-center border-l-0 py-4">I
        Want to:</h2>
    <div class="flex flex-row justify-center w-full shadow-sm text-center" x-data="{ rvalue : 'student' }">
        <label for="student" class="rounded-l-md shadow-sm border-gray-300 font-bold border w-full py-2 px-4"
                :class="{'bg-violet-800 text-white' : rvalue === 'student'}">
            <div class="cursor-pointer">
                <input x-model="rvalue"
                        type="radio"
                        id="student"
                        name="role"
                        value="student"
                        class="hidden"
                        checked />Find a Teacher
            </div>
        </label>

        <label for="teacher" class="rounded-r-md border-gray-300 font-bold border border-gray-400 border-l-0 w-full py-2 px-4"
                :class="{'bg-violet-800 text-white' : rvalue === 'teacher'}">
            <div for="teacher" class="cursor-pointer">
                <input x-model="rvalue"
                        type="radio"
                        id="teacher"
                        name="role"
                        value="teacher"
                        class="hidden">Work as a Teacher
            </div>
        </label>
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

How it works:

  1. We set a x-data with a default value
  2. Each radio uses same x-model and updates value if checked
  3. We dynamically set tailwindcss class based on value of our model

Thanks 😅

Top comments (0)