When you are working on a complex UI, you may need to hide or show an element based on a checkbox. Developers often use Javascript for this purpose but this functionality can be achieved with TailwindCSS.
Hiding or Showing Element with Checkbox
TailwindCSS provides peer
with different modifiers that you can use to hide or show any element. In this example, a checkbox is used with checked
modifier to hide or show an input element. You can check the code below and also the working example online.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<div class="flex h-screen justify-center items-center flex-col"> <form class="space-y-5"> <h1 class="text-3xl font-semibold text-gray-800">Fill the form for tax information</h1> <div> <input type="text" class="w-full py-2 border border-gray-500 rounded-md px-3" placeholder="Total Tax" /> </div> <div> <input type="checkbox" name="agree" id="agree" class="peer w-4 h-4" /> <label for="agree" class="ml-3">Tick this checkbox If you live in USA </label> <div class="mt-3 invisible peer-checked:visible"> <input type="text" class="w-full py-2 border border-gray-500 rounded-md px-3" placeholder="NTN Number" /> </div> </div> <div class="flex justify-end"> <button type="submit" class="bg-blue-500 px-5 py-2 rounded-md text-white"> Submit </button> <div> </form> </div> |
The peer
with different modifiers will only work on sibling elements. This peer
works with every pseudo-class modifier available in CSS, for example peer-focus
, peer-required
, and peer-disabled
.
Conclusion
The peer
with different pseudo-class modifiers can be used with checked
to hide or show an element using TailwindCSS. It helps in adding different elements based on a condition. For example, showing an input if a checkbox is checked, displaying submit button only when the user agrees with terms and conditions.