Skip to content

Instantly share code, notes, and snippets.

@joemasilotti
Created October 19, 2022 20:51
Show Gist options
  • Save joemasilotti/069f80cd0e2cd2bd0bf192c11d90035b to your computer and use it in GitHub Desktop.
Save joemasilotti/069f80cd0e2cd2bd0bf192c11d90035b to your computer and use it in GitHub Desktop.
Tailwind CSS v3.2 data attribute variants + Stimulus
<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>
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"
}
}
@joemasilotti
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment