Integration with Turbo
See original GitHub issueHi Chris,
First of all, great work on this project 👍🏼
I am looking into fixing an issue I’ve found whist using the dropdown component in a Turbo/Rails setup.
The dropdown is working as expected, the issue occurs when navigating back to the screen where the dropdown link was clicked (via the back button), the dropdown remains open:
https://user-images.githubusercontent.com/1736807/109223227-3d399500-77b2-11eb-9b68-45d2872c969a.mov
Adding data-turbo="false"
to the dropdown options solves the issue, so it’s definitely a turbo related problem.
I was hoping that by adding a this.hide()
call, as part of the disconnect()
method, would achieve the desired solution:
diff --git a/src/dropdown.js b/src/dropdown.js
index de8a0bf..ff2c64e 100644
--- a/src/dropdown.js
+++ b/src/dropdown.js
@@ -49,6 +49,7 @@ export default class extends Controller {
if (this.hasButtonTarget) {
this.buttonTarget.removeEventListener("keydown", this._onMenuButtonKeydown)
}
+ this.hide();
}
@@ -125,7 +126,7 @@ export default class extends Controller {
}
hide(event) {
- if (this.element.contains(event.target) === false && this.openValue) {
+ if ((event === undefined || this.element.contains(event.target) === false) && this.openValue) {
this.openValue = false
}
}
However, the hide does not occur until the page is redisplayed:
https://user-images.githubusercontent.com/1736807/109224200-89d1a000-77b3-11eb-82c9-b12a3828034e.mov
As a workaround, I’ve added a turbo:before-cache
to hide the dropdown e.g:
$(document).on('turbo:before-cache', function() {
$('[data-controller="dropdown"] [data-dropdown-target]').addClass('hidden');
});
If you have any ideas on how tailwindcss-stimulus-components could be modified to accommodate this issue, I’m happy to implement the change and open a PR. Perhaps it falls outside the scope of tailwindcss-stimulus-components, and using the turbo:before-cache
is the best solution?
Thanks
Issue Analytics
- State:
- Created 3 years ago
- Comments:22 (16 by maintainers)
Top GitHub Comments
Exactly. those were my findings using the modified version that calls hide when the controller disconnects and for either library(turbolinks and turbo)
Would you like me to test against Turbo’s main branch? Did you find an easy way to do this? I have both
turbo-rails
andturbo
checked out locally. I’m assuming the easiest way is to copy the relevant files into my project’snode_modules/@hotwired/turbo/dist/
(andnode_modules/@hotwired/turbo-rails/app/assets/javascripts/turbo.js
)?