Skip to content

Instantly share code, notes, and snippets.

@vicainelli
Created August 18, 2021 21:05
Show Gist options
  • Save vicainelli/e07082f052602c43d353bb125ac4fbaf to your computer and use it in GitHub Desktop.
Save vicainelli/e07082f052602c43d353bb125ac4fbaf to your computer and use it in GitHub Desktop.

Sign Up Form React Typescript

Error message

TypeScript error in FormSignUp.tsx(43,19):
Argument of type '{ [x: string]: string; }' is not assignable to parameter of type 'MyState | ((prevState: Readonly<MyState>, props: Readonly<{}>) => MyState | Pick<MyState, keyof MyState> | null) | Pick<...> | null'.
  Type '{ [x: string]: string; }' is missing the following properties from type 'Pick<MyState, keyof MyState>': name, email, confirm_email  TS2345

    41 | 
    42 |   onChange(e: ChangeEvent<HTMLInputElement>): void {
  > 43 |     this.setState({ [e.target.name]: e.target.value });
       |                   ^
    44 |   }
    45 | 
import React, { Component, ChangeEvent, SyntheticEvent } from "react";
const inputs = [
{
label: "Name",
name: "name",
type: "text",
placeholder: "John Doe",
},
{
label: "Email",
name: "email",
type: "email",
placeholder: "john.doe@broccoli.co",
},
{
label: "Confirm email",
name: "confirm_email",
type: "email",
placeholder: "john.doe@broccoli.co",
},
];
interface MyState {
name: string;
email: string;
confirm_email: string;
}
class FormSignUp extends Component<{}, MyState> {
constructor(props: any) {
super(props);
this.state = {
name: "",
email: "",
confirm_email: "",
};
this.handleSubmit = this.handleSubmit.bind(this);
}
onChange(e: ChangeEvent<HTMLInputElement>): void {
this.setState({ [e.target.name]: e.target.value }); // error
}
handleSubmit(e: SyntheticEvent): void {
// * is Name valid?
// * is Email valid?
// * is Email and Confirm Email same?
e.preventDefault();
}
render() {
return (
<div>
<form data-testid="signup_form" onSubmit={this.handleSubmit}>
{inputs.map((input, key) => {
return (
<div className="mb-4" key={key}>
<label className="text-gray-400 text-sm" htmlFor={input.name}>
{input.label}
</label>
<input
name={input.name}
id={input.name}
type={input.type}
placeholder={input.placeholder}
onChange={this.onChange}
/>
</div>
);
})}
<div>
<input type="submit" value="send" />
</div>
</form>
</div>
);
}
}
export default FormSignUp;
@vicainelli
Copy link
Author

Encontrei a solução

  onChange(e: ChangeEvent<HTMLInputElement>): void {
    this.setState({ [e.target.name]: e.target.value } as Pick<
      MyState,
      keyof MyState
    >);
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment