javascripthtmlreactjstailwind-css

How to show the date picker if I click the parent div after explictly hiding the date type input in React?


So, I am trying to create a component that will show your typical date picker if an user clicks anywhere in the parent div. But I don't want to show the date type input.

<div className="flex flex-row gap-3">
    <div className="p-3 ... rounded bg-white cursor-pointer">
        <p className="font-normal text-sm ...">{date}</p>
        <input type="date" className="hidden" />
    </div>
    <div>{...}</div>
</div>

Solution

  • You can open the picker menu of individual input fields with the showPicker() method using an external event.

    Note: Pickers for date, datetime-local, month, time, week are launched in the same way. They cannot be shown here because live examples run in a cross-origin frame, and would cause a SecurityError

    This does not work in an iframe or in the StackOverflow CodeSnippet! Create your own reproduction based on the code. I have attached the result in the image.

    If you hide the date input field (display: none;), it won't be able to calculate its current position. Instead, make the parent div relative. Position the input in the bottom left corner, and set its height and width to 0.

    result of code snippet

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.25.6/babel.min.js"></script>
    <script src="https://unpkg.com/@tailwindcss/browser@4"></script>
    
    <div id="root"></div>
    
    <script type="text/babel" data-presets="env,react">
    const { useState, useRef } = React;
    
    function DatePickerComponent() {
      const [date, setDate] = useState("");
      const inputRef = useRef(null);
    
      const handleDateOverlay = () => {
        inputRef.current?.showPicker();
      };
    
      const handleDateChange = (e) => {
        setDate(e.target.value);
      };
    
      return (
        <div className="space-x-4 p-4">
          <div
            class="relative cursor-pointer"
            onClick={handleDateOverlay}
          >
            <span className="text-3xl">📅</span>
            <span className="text-lg">{date}</span>
            <input
              ref={inputRef}
              type="date"
              value={date}
              onChange={handleDateChange}
              className="w-0 h-0 absolute bottom-0 left-0 -z-10"
            />
          </div>
        </div>
      );
    }
    
    ReactDOM.render(<DatePickerComponent />, document.getElementById('root'));
    </script>