hans
hans

Reputation: 21

[Error][react-datepicker] Argument of type 'Date | null' is not assignable to parameter of type 'SetStateAction<Date>?

  1. The library was installed to use the react-datepicker and the example code of the official document was obtained.

  2. I wrote the code of the official document in Vcode as it is, so I thought it would work like an official document.

  3. However, it showed an error message in the title and identified a problem that could not be rendered

  4. Is the existing project an impact? Then, a new project was created, only the library was installed, and the reaction was executed, but the same error occurred.

  5. Then, if CodeSandbox has the same environment, will there be an error here? I checked, but it's working fine on CodeSandbox.

  6. tscconfig.json also unified with CodeSandbox, but there was no change in status.

package.json

"@types/react-datepicker": "^4.8.0",
"react": "^18.2.0",
"react-datepicker": "^4.8.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"typescript": "^4.9.4",

Error Message

TS2345: Argument of type 'Date | null' is not assignable to parameter of type 'SetStateAction<Date>'.
  Type 'null' is not assignable to type 'SetStateAction<Date>'.

    return (
         10 |     <div className="App">
      > 11 |          <DatePicker selected={startDate} onChange={(date) => setStartDate(date)} />
           |                                                                            ^^^^
        12 |     </div>
        13 |   );
        14 | }

Error Code (VS Code)

    import React, {useState} from 'react';
    import DatePicker from 'react-datepicker'
    import 'react-datepicker/dist/react-datepicker.css'

    function App() { 
      const [startDate, setStartDate] = useState(new Date())


      return (
       <div className="App">
             <DatePicker selected={startDate} onChange={(date) => setStartDate(date)} /> 
        </div>
      );
    }

    export default App;

But it works too well here. Even if I match the code and box tsconfig.json, the error continues to occur, what should I correct?

Upvotes: 2

Views: 770

Answers (1)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41445

Add a if condition when setting

onChange={(date) => {
  if(date) setStartDate(date)
}}

Or if you want to support null values in the useState, update here

const [startDate, setStartDate] = useState<Date| null>(new Date())

Upvotes: 2

Related Questions