I am new to Typescript but I'm forcing myself to program in it because they say it is "best" practice and beneficial in the long run...
so now I'm trying to use react-phone-input-2
https://www.npmjs.com/package/react-phone-input-2
The example on the page above is for just standard Javascript.
I did follow it...the widget does show up...however I can't type anything inside the input...
In my editor the onChange attribute/prop of the PhoneInput tag has a red squiggly line under it.
When I hover over it shows the following error:
(method) PhoneInputEventsProps.onChange?(value: string, data: {} | CountryData, event: React.ChangeEvent, formattedValue: string): void Type 'Dispatch<SetStateAction>' is not assignable to type '(value: string, data: {} | CountryData, event: ChangeEvent, formattedValue: string) => void'.
Types of parameters 'value' and 'value' are incompatible. Type 'string' is not assignable to type 'SetStateAction'.ts(2322) index.d.ts(26, 5): The expected type comes from property 'onChange' which is declared here on type 'IntrinsicAttributes & PhoneInputProps'
I basically have this at the top:
const [value, setValue] = useState()
Then somewhere in the returned JSX I have:
<PhoneInput
placeholder='Enter phone number'
value={value}
onChange={setValue}
className='block max-w-lg w-full shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm border-gray-300 rounded-md'
/>
How do I adjust the code so the react-phone-input-2 will work for Typescript????
The problem is that you don't give a type or default value to
useState. This means the default value isundefinedand that is the only type that will be allowed for that state.That means that the type
setValuehere is (more or less):And the type of the
onChangeprop is:So the first argument to
onChangewill bestring, but yoursetValuefunction only acceptsundefined.To fix it, you just have to give your state a type. Either explicitly:
Or by letting the type be inferred from the default value:
See playground