reactjstypescriptdatepickerantd

How to put clear button inside calendar modal in antd datepicker component?


I am using andt datepicker component. In my case, the clear icon covers calendar button.

enter image description here

I need to remove the clear button and allow to clear manually. (But, as far as I know, currently it can not be done). Or I need to move the clear button inside calendar modal, for instance, next to Today button. Is it possible?

I tried to set false value to allowClear property. It removes clear button. But, datepicker value can not be cleared manually.


Solution

  • You can use renderExtraFooter to customize the footer. Right now there's no option to add more content with Today button. But you can hide the current Today button and render your custom footer. I rendered a Today and Clear button in datepicker footer and set showNow to false to hide the existing button. You can also check Extra Footer example.

    Here's the complete code

    import { Button, DatePicker, Flex } from 'antd';
    import dayjs, { type Dayjs } from 'dayjs';
    import { useRef, useState } from 'react';
    
    const App = () => {
        const [value, setValue] = useState<Dayjs | null>(null);
        const [open, setOpen] = useState(false);
        const ref = useRef(null);
    
        return (
            <div style={{ display: 'flex', columnGap: '1rem' }}>
                <DatePicker
                    ref={ref}
                    open={open}
                    onOpenChange={setOpen}
                    value={value}
                    onChange={setValue}
                    allowClear={false}
                    showNow={false}
                    renderExtraFooter={() => (
                        <Flex justify='space-between' style={{ paddingBlock: 7 }}>
                            <Button
                                size='small'
                                type='link'
                                onClick={() => {
                                    setValue(dayjs());
                                    // Value is not updated if we close the picker immediately
                                    setTimeout(() => setOpen(false));
                                }}
                            >
                                Today
                            </Button>
                            <Button size='small' danger onClick={() => setValue(null)}>
                                Clear
                            </Button>
                        </Flex>
                    )}
                />
            </div>
        );
    };
    
    export default App;