It is easier to live a complicated life without realising it because of the many supposedly innovations out there. The manufacturers made us believe these gargets are to simplify our lives, but in…
Forms can be considered as the backbone of web applications. How would you get any information from your users without forms? Yes, there are libraries available to easily build forms now ( a nice one is Formik) but having an understanding of how to create forms in React from scratch is beneficial, It’s pretty easy.
In HTML, form types such as <input> <textarea> generally handle their own state and update based on user input. letting the DOM handle user input for you is referred to as uncontrolled input.
Controlled input is letting React handle the state for you as it is mutable. React stores this state in the state property, and can only be updated using solid-state. Hence, the React component that renders the form is now in control of what happens to that form on subsequent user input.
In most scenarios, we will be needing more than one input field from users. To demonstrate this, let’s create a registration form.
let’s start from the top
state → here we are declaring the state using useState hook, user represents the object we inserted into useState, setUser is going to be used to update the state. if you are familiar with React classes,
handleChange → in our handleChange function, we use setUser to update the user state. I am spreading the user object in the setUser, if you don’t do this, setUser is only going to update the last property which is the password so we have to preserve the other properties state by adding them.
we use e[event.target.name]:event.target.value to tell setUser function what property to update based on the name.
The user data which is now stored in state can be passed down to different components as needed.
Because of its common usage, it is paramount to make sure your forms are easy to understand and interact with by all users. not paying attention to accessibility reduces the chances of having users with disabilities interacting with your site form. Little changes can make a lot of difference;
In our form, we used best practices and added accessibly by;
Validation should never be skipped because you should never trust that the user would input the right information. Options are using the inbuilt HTML validation, writing one yourself or using a validation schema. Any option works fine, I recommend using a validation schema like Yup as it makes writing validation for input fields easy. Here’s a Medium link to an article explaining why you need it and how to use it for form validation.
Now that you understand how forms are built with React Hooks, you can choose to either build forms using a form helper or using React hooks.
A Utility token is a token that is issued to finance the development of a project and can then be used to purchase a good or service offered by the issuer of the token, i.e. they have a utility. MINX…