Ask A Question


You’re not receiving notifications from this thread.

How to initialize datepicker in stimulus controller?

Lee Terng Gio asked in Javascript

I'm using datepicker and turbo frame. The datepicker is broken when the frame is replaced. I'm doing turbo:load in javascript file, it works when navigating between pages, but it will be broken when the form is replaced. I'm thinking to initialize datepicker in stimulus controller but I'm not familiar with stimulus. There aren't many documentation on stimulus, any idea?


Turbo:load runs when a page loads, not a frame. It's the same as the old turbolinks event. Frames are independent from page views which means you need to setup a Stimulus controller instead.

Check out stimulus-flatpickr and you won't have to build anything. 👍


For anyone digging into this as of Rails 7, there is a stimulus 3 support issue to deal with here.

Presently it requires a pin to beta version
bin/importmap pin stimulus-flatpickr@beta

You will also need to have some css references, such as to the latest version
<link rel="stylesheet" href="">
otherwise the input field will be deemed as readonly...


i tried all but in the end it breaks all bootstrap when i use flatpickr


Here is my solution: it also works well in Bootstrap modals. year option doesn't work well in modals, to solve the problem i have added the required code.

import Flatpickr from 'stimulus-flatpickr'
export default class extends Flatpickr {
connect() {
//global options
this.config = {
...this.config, //spread options in case some where defined in initialize
enableTime: false,
time_24hr: true
document.addEventListener("focusin", this.getFocus);
// document.addEventListener('focusin', (e) => {
// //not equal to null
// if (".flatpickr-calendar") !== null) {
// e.stopImmediatePropagation();
// }
// });
//always call super.connect()
disconnect() {
document.removeEventListener("focusin", this.getFocus);
getFocus= (e) => {
if (".flatpickr-calendar") !== null) {

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 79,047+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2023 GoRails, LLC. All rights reserved.