I am trying to use typescript and react properly. Right now I am getting stuck using typescript to handle onChange
and onSubmit
events. I dont know what annotations and types to use. I found that in my SignUpForm component, using any
type will remove the errors but I don't feel as this is best practice.
From DefinitelyTyped source code, I am supposed to use ChangeEventHandler<T>
to handle <input>
onchange
but I don't know what Type(T)
to use because Visual Studio Code says I cannot use .currentTarget
or .target
to retrieve the values I want.
For my handleSubmit
method, I think I am supposed to use FormEventHandler
but once again, I don't know what type to pass in. My text editor is also telling me I don't have access to .preventDefault()
as well
SignUpPage.tsx
import React, { FormEventHandler, InputHTMLAttributes, EventHandler } from 'react';
import SignUpForm from './SignUpForm';
interface IProps {}
interface IState {}
class SignUpPage extends React.Component<IProps, IState> {
constructor(props: IProps) {
super(props);
this.state = {
email: "",
}
}
handleSubmit = (event: FormEventHandler<>): void => {
event.preventDefault();
}
handleChange = (event: React.ChangeEventHandler<HTMLInputElement>): void => {
const { value, name} = event.;
this.setState({ [name]: value })
}
render() {
return(
<SignUpForm
handleSubmit={ this.handleSubmit }
handleChange={ this.handleChange }
/>
);
}
}
export default SignUpPage;
SignUpForm.tsx
interface IProps {}
const SignUpForm = ({ handleSubmit, handleChange }: { handleSubmit: any, handleChange: any} ): JSX.Element => (
<form onSubmit={ handleSubmit }>
<input
name="email"
type="email"
onChange={ handleChange }>
</input>
</form>
);
export default SignUpForm;