Created
October 19, 2022 20:51
-
-
Save joemasilotti/069f80cd0e2cd2bd0bf192c11d90035b to your computer and use it in GitHub Desktop.
Tailwind CSS v3.2 data attribute variants + Stimulus
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div data-controller="toggle"> | |
<button type="button" data-action="toggle#toggle">Toggle</button> | |
<div data-toggle-target="element" data-expanded="false" class="data-[expanded=false]:hidden"> | |
Here is some toggle-able content! | |
</div> | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Controller } from "@hotwired/stimulus" | |
export default class extends Controller { | |
static targets = ["element"] | |
toggle(event) { | |
event.preventDefault() | |
const expanded = this.elementTarget.dataset.expanded | |
this.elementTarget.dataset.expanded = expanded == "false" ? "true" : "false" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tailwind CSS introduced data attribute variants in v3.2 to conditionally style things based on data attributes with the new
data-*
variants.This is an example of creating a minimal "toggle" component with Stimulus JS that uses the new feature.