React-calendar: TypeScript error with version 3.3.0

Created on 11 Jan 2021  路  4Comments  路  Source: wojtekmaj/react-calendar

Error

Using the sample code from the GitHub README, I receive the following error. I have installed the @types package also since I am using TypeScript.

Type 'Dispatch<SetStateAction<null>>' is not assignable to type 'OnChangeDateCallback'.
  Types of parameters 'value' and 'date' are incompatible.
    Type 'Date | Date[]' is not assignable to type 'SetStateAction<null>'.
      Type 'Date' is not assignable to type 'SetStateAction<null>'.
        Type 'Date' provides no match for the signature '(prevState: null): null'.  TS2322

    10 |     return (
    11 |         <div>
  > 12 |             <Calendar value={selectedDate} onChange={setSelectedDate} />
       |                                            ^
    13 |         </div>
    14 |     );
    15 | };

Code

My JSX snippet is:

 const [selectedDate, setSelectedDate] = useState(null);

    return (
        <div>
            <Calendar value={selectedDate} onChange={setSelectedDate} />
        </div>
    );

Same error is observed even is I use default new Date for useState hook.

Dependencies

    "@material-ui/core": "^4.11.2",
    "@material-ui/icons": "^4.11.2",
    "@testing-library/jest-dom": "^5.11.6",
    "@testing-library/react": "^11.2.2",
    "@testing-library/user-event": "^12.5.0",
    "@types/jest": "^26.0.18",
    "@types/node": "^14.14.11",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "@types/react-router-dom": "^5.1.6",
    "react": "^17.0.1",
    "react-calendar": "^3.3.0",
    "react-dom": "^17.0.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.1",
    "typescript": "^4.1.2",
    "web-vitals": "^0.2.4",
    "@types/react-calendar": "^3.1.2"
question

Most helpful comment

You must type your state like the onChange callback : Date | Date[].
In your case, you use too a null value.

const [selectedDate, setSelectedDate] = useState<Date | Date[] | null>(null);

All 4 comments

I'm also facing same issue, any solution ?

As this error is in community-powered @types repo, there's nothing we can do here on React-Calendar side.

One possible solution meanwhile is to put it inside an arrow function.

image

image

You must type your state like the onChange callback : Date | Date[].
In your case, you use too a null value.

const [selectedDate, setSelectedDate] = useState<Date | Date[] | null>(null);

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Muttakee31 picture Muttakee31  路  4Comments

Chusynuk picture Chusynuk  路  3Comments

mikeyharris89 picture mikeyharris89  路  4Comments

spoldman picture spoldman  路  4Comments

Coder2012 picture Coder2012  路  5Comments