I have my Object state here written in vanilla javascript. and i wanted to convert it into typescript.
This is the state for formData object.
const [formData, setFormData] = useState({
firstName: "",
lastName: "",
});
This is the handleFormChange function.
const handleFormChange = (event) => {
const { name, value } = event.target;
setForm(prevFormData => (
...prevFormData,
[name]:value;
));
};
on vanilla js it's working perfectly fine. What could be the type definition for
[name]:value;
Input
OnChangeGetting the value from an inputonChangeevent is one of the first things people learn when working with HTML. In a Typescript environment, it can be tempting to use any as a type for theonChangeevent. Instead of any , you canuseReact.ChangeEvent<HTMLInputElement>
const onChange = (event: React.ChangeEvent<HTMLInputElement>) =>
//That will give you access to all the values included in the input onChange event.
If you are using a text area and need to differentiate the event, you can use this instead:
const onChange = (event: React.ChangeEvent<HTMLTextAreaElement>) =>
You should also share your setForm function here so I can try to answer your question based on that. Actually it would be even better if you could share your code with a CodeSandbox link. Btw this is not Vanilla JS, you use React's useState. I would suggest you to check React TypeScript CheetSheet.