1

I'm trying to render the input values from the start and end dates on the calendar (react-datepicker) component into a list. Currently, I can log the current value but need to figure out a way to store the start and end values in the state. I'm sure this is a simple fix, but I'm having trouble figuring it out. Any help would be appreciated!

const Calendar = () => {
  const [startDate, setStartDate] = useState(null);
  const [endDate, setEndDate] = useState(null);

  return (
    <>
      <DatePicker
        placeholderText="Start"
        showTimeSelect = {true}
        isClearable={true}
        selected={startDate}
        onChange={date => setStartDate(date)}
        selectsStart
        startDate={startDate}
        endDate={endDate}
      />
      <DatePicker
        placeholderText="End"
        showTimeSelect = {true}
        isClearable={true}
        selected={endDate}
        onChange={date => setEndDate(date)}
        selectsEnd
        startDate={startDate}
        endDate={endDate}
      />

      <div>Start date={startDate ? startDate.toString() : null}</div>
      <div>End date={endDate ? endDate.toString() : null}</div>
    </>
  );
};
Alex Yepes
  • 1,160
  • 1
  • 9
  • 21
kapa
  • 35
  • 5
  • I don't understand the problem. What do you mean when you say you want to store the state over time? Do you want to be able to access these date values across different components, do you want to persist them regardless of page reload? – 5eb Jan 20 '21 at 21:59

1 Answers1

0

You are already setting the state correctly. However, the value stored in the state is an object type, so it needs to be converted to be rendered properly. You can do it like this:

<div>Start date={startDate ? JSON.stringify(startDate) : null} </div> 

This will give you the date and time in UTC

Or you can also use a library called moment.js https://momentjs.com/ which you can use to convert the object to the format you want. Install it first: "npm i moment" and then, something like this:

import moment from "moment";

<div>Start date={startDate ? moment(startDate).format("YYYY-MM-DD HH:mm:ss") : null} </div>
Alex Yepes
  • 1,160
  • 1
  • 9
  • 21