Home  >  Q&A  >  body text

Get value of button click in React Flatpickr

I have a component in React and attached react-flatpicker to get the date value. However, after I use useRef, it shows the value as "may be null", and yes, after console.log, the result is the same:

<Flatpickr
    ref={fp}
    name="startTime"
    className="py-2 bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
    options={{enableTime: true, noCalendar: true, dateFormat: "H:i",}}
/>

This is the function:

const fp = useRef(null);
function handleSubmitAgenda() {
    console.log(fp?.current?.value);
}

Please give me some inspiration.

P粉446800329P粉446800329363 days ago564

reply all(1)I'll reply

  • P粉692052513

    P粉6920525132023-09-22 13:48:55

    To get the value from the React Flatpickr component when you click the button, you need to use the onChange property provided by Flatpickr.

    Please view the code base below.

    import { useState, useRef } from "react";
    import Flatpickr from "react-flatpickr";
    
    function YourComponent() {
      const [selectedDateTime, setSelectedDateTime] = useState(null);
      const fp = useRef(null);
    
      // 处理日期/时间选择变化的函数
      const handleDateTimeChange = (selectedDates) => {
        setSelectedDateTime(selectedDates[0]);
      };
    
      function handleSubmitAgenda() {
        console.log(selectedDateTime); // 当点击按钮时,这将记录所选的日期/时间
      }
    
      return (
        <div>
          <Flatpickr
            ref={fp}
            name="startTime"
            className="py-2 bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
            options={{
              enableTime: true,
              noCalendar: true,
              dateFormat: "H:i",
            }}
            onChange={handleDateTimeChange} // 在日期/时间选择变化时调用handleDateTimeChange
          />
    
          <button onClick={handleSubmitAgenda}>提交</button>
        </div>
      );
    }

    Hope it helps you. good luck.

    reply
    0
  • Cancelreply