How to hide the date input of react-datepicker and only show the calendar on icon-click

Post author: Adam VanBuskirk
Adam VanBuskirk
7/2/23 in
Tech
ReactTypeScript

I’m writing software that allows the user to select a date. This software is written in React. I decided to use the react-datepicker package. However, I didn’t want the ugly date textbox that the user can type in. Instead, I wanted a single icon that the user can click and select a date from a datepicker. This post shows how I did it.

The User Interface

The CSS

.react-datepicker-wrapper {
  display: none !important;
}

.react-datepicker-popper {
  z-index: 9999 !important;
}

The React Code

I removed the code not relevant to the date picker.

import { useState } from 'react';
import { Link } from 'react-router-dom';
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { IoCalendarOutline } from 'react-icons/io5';
import { AiOutlineSync } from 'react-icons/ai';

function Loads() {
 
    const [scheduleDate, setScheduleDate] = useState<Date>(new Date("2023-06-14T05:00:00.000+00:00"));
    const [showDatePicker, setShowDatePicker] = useState(false);
  
    const changeDateHandler = (e: React.MouseEvent<HTMLAnchorElement>) => {
        e.preventDefault();
        setShowDatePicker(!showDatePicker);
    }

    return (
        <>
            <div id="load" className="mt-2 ms-4 me-4"> 
                <div className="row mt-2 mb-2">
                    <div className="col-6">
                        <Link to="/" onClick={(e) => syncHandler(e)} className="pe-2">
                            <AiOutlineSync size={32} />
                        </Link>
                        <Link to="/" onClick={(e) => changeDateHandler(e)}>
                            <IoCalendarOutline size={32} />
                        </Link>               
                        <DatePicker selected={scheduleDate} onChange={(date: Date) => { setScheduleDate(date); setShowDatePicker(false) }} open={showDatePicker} />
                    </div>
                </div>
            </div>
        </>
    );
}

export default Loads;

Sign up today for our weekly newsletter about AI, SEO, and Entrepreneurship

Leave a Reply

Your email address will not be published. Required fields are marked *


Read Next




© 2024 Menyu LLC