onesine / react-tailwindcss-datepicker

Modern date range picker component for React using Tailwind 3 and dayjs. Alternative to Litepie Datepicker.
https://react-tailwindcss-datepicker.vercel.app/
MIT License
505 stars 147 forks source link

I want the date picker modal to be open by default when the page loads, i didn't saw anything #256

Open rahabonyani opened 1 month ago

MeepCastana commented 3 weeks ago
import React, { useEffect, useRef } from 'react';
import Datepicker from 'react-tailwindcss-datepicker';

const Test = () => {
  const datepickerWrapperRef = useRef(null);

  useEffect(() => {
    const openDatepicker = () => {
      setTimeout(() => {
        const inputElement = datepickerWrapperRef.current?.querySelector('input');
        if (inputElement) {
          inputElement.focus(); 
          const clickEvent = new MouseEvent('click', { bubbles: true });
          inputElement.dispatchEvent(clickEvent);
        }
      }, 500); 
    };

    openDatepicker();
  }, []);

  return (
    <div ref={datepickerWrapperRef}>
      <Datepicker
      />
    </div>
  );
};

export default Test;

If you want to ensure your datepicker opens automatically when the page loads, you can use a combination of React hooks and a simulated click event. Here's how:

Reference the Wrapper div

Create a useRef hook to reference the div containing the Datepicker component. This will allow you to interact with the DOM element directly.

Use setTimeout to Delay the Click Event

To make sure the simulated click event is dispatched after the component is fully rendered, use the setTimeout function. This will delay the click event, allowing the DOM to be completely ready.