What are the types of React.js's state and event?
In my code below, I can only make it work by using type: any
but it's just a hack. How can I use the right types for them?
In my custom hooks:
If I use function useFormFields(initialState: object)
, I get:
// value={inputs.item} error:
Property 'item' does not exist on type 'object'.ts(2339)
// onChange function error:
(JSX attribute) onChange: object
No overload matches this call.
If I use function(event: React.FormEvent)
(which is true), I have this error:
Property 'id' does not exist on type 'EventTarget'.ts(2339)
If I use function(event: object)
, I have this error:
Property 'target' does not exist on type 'object'.ts(2339)
That's odd because below I use const handleSubmitItem = (event: React.FormEvent)
and it works.
The answers I've found (like this one) don't work for me because Property 'id' does not exist on type 'EventTarget'
import React, {useState} from 'react';
import TextField from '@material-ui/core/TextField';
import IconButton from '@material-ui/core/IconButton';
import AddShoppingCartIcon from '@material-ui/icons/AddShoppingCart';
/**
* Custom hooks for input fields.
* @param initialState initialState for Input Fields
*/
function useFormFields(initialState: any) {
const [inputs, setValues] = useState(initialState);
return [
inputs,
function(event: any) {
setValues({
...inputs,
[event.target.id]: event.target.value
});
}
];
}
export default function FormPropsTextFields() {
const [inputs, handleInputChange] = useFormFields({
item: '',
quantity: '',
store: ''
});
const handleSubmitItem = (event: React.FormEvent) => {
event.preventDefault();
console.log(inputs);
};
return (
<form
className={classes.root}
noValidate autoComplete="off"
onSubmit={handleSubmitItem}
>
<div>
<TextField
required id="item"
label="Item"
value={inputs.item}
onChange={handleInputChange}
/>
<TextField
id="quantity"
label="Quantity"
type="number"
value={inputs.quantity}
onChange={handleInputChange}
InputLabelProps={{
shrink: true,
}}
/>
<TextField
id="store"
label="Store"
type="search"
value={inputs.store}
onChange={handleInputChange}
/>
<IconButton
type="submit"
color="primary"
aria-label="add to shopping cart"
>
<AddShoppingCartIcon />
</IconButton>
</div>
</form>
);
}