Hi there!
Today we are going to create a Sign up form in React using TypeScript, I'll walk you through the process step by step and explain each step as clearly as possible. Before we jump right in, make sure you've created a react app with typescript template. If you have not you can go ahead and execute the following command in your terminal:
create-react-app form --template typescript
or
yarn create react-app form --template typescript
In our App, let's go ahead and clear the header element and replace it with HTML form
tags. Here's how the code looks now:
In the next step, we'll add the input fields and labels to the form element to give it a structure. We'll include first name, last name, email, and password for now.
Now Let's add a little bit of functionality to the code.
When the user fills in the inputs fields with the appropriate data, we want to take the inputs and store them in an object which later on will be sent to the server and eventually stored in the database.
In typescript, it's considered best practice to create interfaces of classes or objects to kind of ease the process of collaboration and code maintenance. Interface lets TypeScript know what data types to expect from an object or a class. In our case, we'll name the interface SingnUpFormState.
which will expect four strings values from the following keys: firstname, lastname, email
and password
interface SignUpFormState {
firstname: string;
lastname: string;
email: string;
password: string
}
In the next step, import useState
form react and declare a hook inside the function referencing the interface we created earlier and assign the object keys empty strings :
const [formData, setFormData] = useState<SignUpFormState> ({
firstname: '',
lastname: '',
email: '',
password: ''
})
Next, we'll now create a function handleChange
that will keep track of the data passed into the input fields.
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const {name, value} = e.target;
setFormData(prevData => ({...prevData, [name]: value}))
}
The 'e: React.ChangeEvent<HTMLInputElement>
' parameter, is an object which represents the changes made in the input fields.
The properties name
and value
are extracted from the event target
. The name
property corresponds to the name of the input while the value
property is assigned to the data passed to the input.
Then the setFormData
function updates the formData
Object by copying the values obtained from the form and assigning the newly obtained values to the object's keys i.e('firstname, lastname, email, password'
) as their respective values.
In the following step, we are creating a function that will handle what will be done to the form when the button sign up
is clicked.
Make sure to install axios
in your project.
const handleSubmit = async (e: React.ChangeEvent<HTMLFormElement>) => {
e.preventDefault();
try {
const response = await axios.post('http://localhost:8080/apiv1/signup', formData);
console.log(response);
}catch (error) {
console.error(error);
}
}
Inside a try-catch block, an HTTP POST request is made using Axios. The axios.post
function is used to send a POST request to the specified URL '
http://localhost:8080/apiv1/signup
'
, with the form data (formData
) as the request payload. We haven't created the endpoint yet, so we'll log the response
data to the console for now. (We'll cover the server side in the next article)
If some sort of error occurs during the request, it is caught in the catch
block. The error object is logged to the console using console.error(error)
. You can customize this block to handle the error in our application.
The final step is to add value
to the input fields, in order for the values passed by the user to be tracked. We'll also add the handleChange function and handleSubmit button :
If we console.log formData
you'll notice that everytime you type in any of the input fields, it updates the value of the Object's keys.
You might have noticed that you got an error. This is because we haven't set up the server side yet where the user's details are being sent to:
In the next article, we'll create a simple backend server to receive the user's details and store them in a database.
GitHub repo: https://github.com/luqmanshaban/form-client
I would greatly appreciate your feedback and suggestions regarding this article. If you notice any errors or have any recommendations for improvement, please feel free to share them below. Your input is invaluable in helping me provide accurate and engaging content.
Connect with me: