Search code examples
javascriptreactjsantd

Is there a way to bind the selected date in a calendar date picker to a variable that can be accessed by another file?


I am working on a React application and currently have a date picker to select a date range using Ant Design. I want to store the value of the selected date into a variable that can be accessed by another file in my program. How can I bind the selected value into a variable? Here is the JavaScript code for my date picker:

 <p>Select a date range: </p>
              </div>
              <div className="left">
              <Space direction="vertical" size={12}>
                <RangePicker
                  format="YYYY-MM-DD"
                  onChange={this.onChange}
                  onOk={onOk}
                />
              </Space>

Solution

  • Check the following example, You can store the date values in a variable once the date is selected and onChange function is called.

    import React, { useState } from 'react';
    import ReactDOM from 'react-dom';
    import { DatePicker, Space } from 'antd';
    import 'antd/dist/antd.css';
    import './index.css';
    
    const { RangePicker } = DatePicker;
    
    const Demo = () => {
      let selecteddate;
      let selectedstartdate;
      let selectedenddate;
    
      const onChange = (value) => {
        selecteddate = value;
        selectedstartdate = value[0];
        selectedenddate = value[1];
    
        //Pass the following values
         console.log("selecteddate:",selecteddate);
         console.log("selectedstartdate:",selectedstartdate);
         console.log("selectedenddate:",selectedenddate);
      };
    
      return (
        <>
          <p>Select a date range: </p>
          <Space direction="vertical" size={12}>
            <RangePicker format="YYYY-MM-DD" onChange={onChange} />
          </Space>
        </>
      );
    };
    
    export default Demo
    

    Screenshot

    screenshot