Create toggle with tailwind and alpinejs
I know this is a pretty dry read, but it's here in case someone or future me does a google search.
If you have any questions please let me know in the 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>
How it works:
We set a
x-data
with a default valueEach radio uses the same
x-model
and updates value ifchecked
We dynamically set tailwindcss class based on the value of our model
Thanks ๐
ย