Search code examples
javascriptreactjsantd

DatePicker.RangePicker from antd not working properly in a Function Component in React


I am working with React and the antd library, and I am trying to use the DatePicker.RangePicker in my project. When I place the RangePicker directly inside the component, it works fine.

However, in order to make my component more readable, I decided to split part of it into a separate Function Component. But in this Function Component, the component re-renders every time the useState is used to update the state, causing the RangePicker not to display properly. Here is my code:

const ProductEmissions: React.FC = () => {
const RenderSearch: React.FC = () => (
        <Form onFinish={onSubmit} style={{ width: '100%' }} form={form}> }}>
         <Text className='label'>Date</Text>
         <Form.Item name='month'>
           <DatePicker.RangePicker
              value={dates || value}
              disabledDate={disabledDate}
              onCalendarChange={(val) => setDates(val)}
              onChange={(val) => setValue(val)}
              onOpenChange={onOpenChange}
              style={{ width: '100%' }}
            />
          </Form.Item>
        </Form>
    );
 return (
        <Layout>
            <ContentArea>
                <RenderSearch />
            </ContentArea>
        </Layout>
    )
};

How can I solve this issue in order to use DatePicker.RangePicker properly within a Function Component?


Solution

  • Try to wrap the nested component in useMemo to trigger re-render only when th e properties in the dependency array changes:

    const ProductEmissions: React.FC = () => {
    
      const renderSearch = useMemo(() => (
        <Form onFinish={onSubmit} style={{ width: '100%' }} form={form}>
          {' '}
          }}>
          <Text className='label'>Date</Text>
          <Form.Item name='month'>
            <DatePicker.RangePicker
              value={dates || value}
              disabledDate={disabledDate}
              onCalendarChange={(val) => setDates(val)}
              onChange={(val) => setValue(val)}
              onOpenChange={onOpenChange}
              style={{ width: '100%' }}
            />
          </Form.Item>
        </Form>
      ), [value]); // Will be re-rendered only when value changes
    
      return (
        <Layout>
          <ContentArea>
            {renderSearch}
          </ContentArea>
        </Layout>
      );
    };