Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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)}
                />

>Solution :

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>
  );
}

The working demo is live here: https://codesandbox.io/s/xenodochial-feather-t2heml?file=/src/App.js:0-739

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading