I am trying to learn React and React Hooks. I have created custom hook that lives in another file: CustomHook.ts. I am using it in my ContactForm.tsx. The problem I am having is inside each value={inputs.property} in the <input /> tags. Typescript is unable to resolve the types of each inputs._propertyName.
I have defined an interface IContact that defines the types I would like to use. I am NOT currently using this interface as I don't know where to put it.
Any help would be greatly appreciated!
Error:
ERROR in /jefthimi/src/components/Contact/ContactForm.tsx(35,31)
TS2339: Property 'subject' does not exist on type '{}'.
ERROR in /jefthimi/src/components/Contact/ContactForm.tsx(46,31)
TS2339: Property 'email' does not exist on type '{}'.
ERROR in /jefthimi/src/components/Contact/ContactForm.tsx(57,31)
TS2339: Property 'name' does not exist on type '{}'.
ERROR in /jefthimi/src/components/Contact/ContactForm.tsx(68,31)
TS2339: Property 'comments' does not exist on type '{}'.
ContactForm.tsx
import React from 'react';
import './ContactForm.scss';
import useContactForm from './CustomHook';
interface IContact {
subject: string;
email: string;
name: string;
comments: string;
}
const message = (inputs: any) => {
alert(`Message Sent!
Subject: ${inputs.subject}
Sender: ${inputs.email}
Name: ${inputs.name}
Comments: ${inputs.comments}`);
};
const { inputs, handleInputChange, handleSubmit } = useContactForm(message);
export default class ContactForm extends React.Component {
render() {
return (
<div className="contactForm_container">
<div className="contactForm_inner">
<form onSubmit={handleSubmit}>
<div className="input-group">
<label htmlFor="subject">Subject</label>
<input
id="subject"
name="subject"
type="text"
onChange={handleInputChange}
value={inputs.subject}
required
/>
</div>
<div className="input-group">
<label htmlFor="email">Your Email</label>
<input
id="email"
name="email"
type="text"
onChange={handleInputChange}
value={inputs.email}
required
/>
</div>
<div className="input-group">
<label htmlFor="name">Your Name</label>
<input
id="name"
name="name"
type="text"
onChange={handleInputChange}
value={inputs.name}
required
/>
</div>
<div className="input-group">
<label htmlFor="comments">Comments</label>
<textarea
name="comments"
id="comments"
rows={10}
onChange={handleInputChange}
value={inputs.comments}
required
/>
</div>
<div className="controls">
<button type="submit">Send Message</button>
</div>
</form>
</div>
</div>
);
}
}
CustomHook.ts
import React, { useState } from 'react';
/*
This is a Custom React Hook that handles our form submission
*/
const useContactForm = (callback) => {
const [inputs, setInputs] = useState({});
const handleSubmit = (event) => {
if (event) {
event.preventDefault();
}
callback();
};
const handleInputChange = (event) => {
event.persist();
setInputs((inputs) => ({
...inputs,
[event.target.name]: event.target.value
}));
};
return {
handleSubmit,
handleInputChange,
inputs
};
};
export default useContactForm;