Encountered an error while trying to access the 'add' property of an undefined object in Flatpickr integration with Vue.js

I'm currently attempting to integrate flatpickr into a Vue component that will then send dates to an eventHub. Unfortunately, I'm encountering difficulties as flatpickr appears to be unable to locate the input field.

The structure of my wrapper component is as follows:

<template>
<input type="text" id="flatpickr" placeholder="Select a range" />
</template>

<script>
const Flatpickr = require("flatpickr");

var defaultStart = new Date(new Date().setDate(new Date().getDate() - 10)).toISOString().slice(0, 10)
var defaultEnd = new Date().toISOString().slice(0, 10)

export default {
  name: 'DatePicker',
  props:['startDate', 'endDate'], // Although not required, all Children should receive data
  mounted() {
    new Flatpickr('#flatpickr', {
      dateFormat: "Y-m-d",
      mode: 'range',
      altInput: true,
      minDate: new Date().fp_incr(-60),
      maxDate: defaultEnd,
      locale: { firstDayOfWeek: 1},
      onClose: function(selectedDates, dateStr, instance) {
        let startDate = selectedDates[0].toISOString().slice(0, 10);
        let endDate = selectedDates[1].toISOString().slice(0, 10);
        this.$emit('change', { startDate, endDate });  
      }
    })
  }
}
</script>

I've attempted using .class-name as well, but without success. Can anyone help me identify the issue?

Answer №1

Consider implementing the following adjustments:

Within your template...

<input type="text" ref="flatpickr" placeholder="Click to select date" />

Inside the mounted() lifecycle hook...

mounted() {
    const inputElement = this.$refs.flatpickr;
    new Flatpickr(inputElement, { 
Explanation:

The Vue conventions recommend using "ref" instead of "id" to reference elements in the template. It is essential to adhere to these guidelines as Vue handles templates differently from plain HTML and unexpected behaviors may occur if treated otherwise. Remember that although it looks like HTML, the Vue template actually gets compiled into a function.

Replace the id attribute of the input with a ref attribute, obtain a reference to the input element within the mounted() hook, and utilize it as the first argument when calling the Flatpickr() method instead of an "#id".

Explore this implementation on JSFiddle: https://jsfiddle.net/CookieJon/7stotLrz/2/

Answer №2

Why not try using this fantastic Vue component instead?


Installation is a breeze:

npm install vue-flatpickr-component --save

It's incredibly easy to implement.

Here's a sample:

<template>
  <div>
    <flat-pickr v-model="date"></flat-pickr>
  </div>
</template>

<script>
  import flatPickr from 'vue-flatpickr-component';
  import 'flatpickr/dist/flatpickr.css';

  export default {    
    data () {
      return {
        date: null,       
      }
    },
    components: {
      flatPickr
    }
  }
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Does adding the async attribute to a script impact the timing of the onload event?

I am facing an issue with a webpage that contains a script tag in the HEAD section: <script src="somescript.js" type="text/javascript" async></script> Since it has the async attribute, this script loads asynchronously, allowing the browser to ...

"Trying to access jQuery .slide and .slideUp features, but unfortunately they are

I've created this script: $("#comments .comment .links").hide(); $("#comments .comment").hover( function() { $(".links", this).stop(true).slideDown(300); }, function() { $(".links", this).stop(true).slideUp(300); } ); However, I'm facin ...

Tips for allowing the parent component to initiate the child component's event in VueJs without relying on refs

<template v-for='item in 777'> <ParentComponent> <ChildComponent / </ParentComponent> </template> Seeking a more graceful solution to have events triggered in ChildComponent by events in ParentComponent ...

The filter function is failing to return the initial element of the array, contradicting what is displayed in the console.log output

When given two arrays of integers, I aim to create a new array containing only the unique values from both input arrays. There are many methods for achieving this, but I'm curious as to why my current approach is not producing the desired result. cons ...

Can you explain the concept of a read-only property in JavaScript and its significance?

I'm a bit puzzled about the concept of a read-only property. While MDN defines classList as such, can you clarify what this really entails? ...

Connect controls to elements within a sibling component

My ImagesInput component utilizes an array called images to display the images. I have added a button for changing the images, but I am facing an issue in separating and changing the correct image. It seems to only modify the last index of each gallery a ...

What is the process for inserting a key value pair into a JSON object?

I am looking to enhance my JSON data by including a key-value pair in each object within the array. https://i.sstatic.net/48ptf.png My goal is to insert a key-value pair into every object in the students array. ...

Sending an array to a different function within ReactJS

Struggling with a somewhat simple React question at the moment: readData: function(){ var readFromCpDev1 = firebase.database().ref('environments/' + 'cp-dev1'); var envUsersArray = []; readFromCpDev1.on('value', ...

Ensure Focus Retention Upon Clicking Inside Iframe with li a:focus

How can I prevent my ul.SideNav_Main li a:focus class from losing focus when I click on the iframe or elsewhere on the page? Shouldn't it maintain focus until I click on another URL in the list? Is it possible to solve this issue with just CSS, or wo ...

Adjustable div height: reduce until reaching a certain point and then begin expanding once more

Incorporating a hero section to display content is my current approach. The design adapts responsively utilizing the padding-bottom percentage strategy, along with an inner container that is absolutely positioned for central alignment of the content. The ...

Can the conventional HTML context menu be swapped out for a link context menu instead?

Currently, I am working on developing a custom linkbox component that is similar to the one found on this page: Here is an example of the code: export const Linkbox = ({}) => { const linkRef = useRef(null); return ( // eslint-disable-next-l ...

Combining httpProvider responseInterceptor with $http error callback does not function properly

In my application, I implemented a "loading screen" feature inspired by this post: 'Click' However, I am facing an issue where all $http requests are triggering the "success" callback, even for URLs that do not exist. $http.post("this doesnt ev ...

Maintain the selected bootstrap tab even after the page is refreshed, even when the content is loaded dynamically

I am currently facing an issue with loading tabs using Angular. Whenever a tab is clicked, the id is saved to localStorage. Now, I want to programmatically click on the same tab using jQuery when the page refreshes. However, since the DOM element for the ...

Removing connected entries with pre middleware on mongoose

I currently have 3 different schemas: Building const BuildingSchema = mongoose.Schema({ address: { type: String, required: true }, numberOfFloors: { type: Number, default: 0 }, }); Apartment const RoomSchema = mongoose.Schema({ roomNumber: { type: ...

How can I prevent nested setTimeout functions with identical names from occurring?

Attempting to utilize nested timeOut with the same names, which functions similar to a loop, although not exactly. An example that I tried is: let i = 1; setTimeout(function run() { func(i); setTimeout(run, 100); }, 100); which was taken from this li ...

Tips for embedding HTML components within a div element through JavaScript

Can you help me transform this code into a div element using JavaScript? <div id=parentDiv> <div id="question1"> QuestionNo 1 <button onclick="setOption(1,1)">A</button> <button onclick="setOption(1, ...

Incorporate functionality into a button using jQuery

I am working on a table that displays data in different levels (Parent, Child, Grandson). When I click on the parent row, it expands to show new rows related to the child level. Similarly, clicking on a child row reveals a third level known as the grandson ...

what is the best way to display a chosen value in a dropdown menu using jQuery?

How can I display a value from a database in a select option? This code is written in PHP, JSON, AJAX, and JQUERY. $(document).on('click', '.edit_data', function () { var shop_id = $(this).attr("id"); $.ajax({ url: "&l ...

Cannot adjust expiration date of express-session in browser

In my current project, I am utilizing express-session. Let's say a session has been created between the web browser and the Node.js server with a default expiration time of one hour. At this point, there is a cookie named connect.sid stored in the use ...

Adding content into a designated position in a document

My challenge is to find the index of user-provided data in order to insert new data at that specific point. I am familiar with array insertion methods, but extracting the index provided by the user is where I'm stuck. My current approach involves filt ...