Search code examples
reactjsdayjs

how to set default value in a input type datetime local field when using dayjs?


I want to set a default date in my input date field but its not working.

 const [defaultDateFrom, setDefaultDateFrom] = useState<dayjs | null>(null);

 const dd = new Date(currentYear, currentMonth, currentDay, 10);
 const d = dayjs(dd).add(1, 'day');
 setDefaultDateFrom(d);

  <section className="date-container">
    <input type="datetime-local" value={defaultDateFrom} />
  </section>

What I am doing wrong ?


Solution

  • The datetime-local input requires a string value in a specific format. You are passing in a dayjs object. The solution is to format the object to a datetime string, like this:

    const d = dayjs(dd).add(1, "day").format("YYYY-MM-DDThh:mm")
    

    You can check out a working example here.

    Also note that in your example, the component re-renders indefinitely.