24sharon
24sharon

Reputation: 1975

react useState and dates with inputs type text

I have 2 problems

  1. to set the default value to current date
  2. to view and change the date by using the html input type of date

How can I make it work

this is my sample code:

    const [fromDate, setFromDate] = useState(new Date())
<input
                    className={`form__input  ${!fromDate &&'form__input--incomplete'}`}
                    id="fromDate"
                    name="fromDate"
                    type="date"
                    autoComplete="off"
                    value={fromDate}
                    onChange={(e)=>setFromDate(e.target.value)}
                />

Upvotes: 2

Views: 3920

Answers (1)

dreambold
dreambold

Reputation: 3050

Here's the solution:

import { useState } from "react";
    
export default function App() {
  const [fromDate, setFromDate] = useState(new Date());
  return (
    <div className="App">
      <input
        // className={`form__input  ${!fromDate && "form__input--incomplete"}`}
        id="fromDate"
        name="fromDate"
        type="date"
        autoComplete="off"
        value={
          fromDate.getFullYear().toString() +
          "-" +
          (fromDate.getMonth() + 1).toString().padStart(2, 0) +
          "-" +
          fromDate.getDate().toString().padStart(2, 0)
        }
        onChange={(e) => {
          setFromDate(new Date(e.target.value));
        }}
      />
    </div>
  );
}

Upvotes: 3

Related Questions