Forms using React.js
There are a ton of topics to talk about when we discuss React. What are the nuances that differentiates plain vanilla JavaScript from React and how do you utilize React’s full potential. Assuredly, it is continuous learning and no matter how skilled and knowledgeable you are, you still have something to learn. Being relatively new to React.js, I would love to share some great nuggets learnt over time. Today, we start with forms.
React forms are controlled components, similar to but unlike regular JavaScript forms. While react forms are controlled components, JavaScript forms are uncontrolled components. Here are a few things to know about React forms.
Converting uncontrolled forms to controlled (React) forms.
The above is a simplified summary that gives you the picture pf what you need to do to have a controlled form. To be able to achieve this, here are a few more learning points you need to know;
Here is a breakdown of the learning points listed above.
React form hooks the state to the text input using 2 props. One react hook forms use is the value prop, and it converts the state input to controlled. Then, the onChange event receives all the keystroke changes to update the input.
领英推荐
Creating the submit button requires that the submit button default behavior is disabled. Default form action is normally activated when the submit button is pressed on a regular form. In an uncontrolled form, activating the submit button triggers a get request to root and a page refresh.
On traditional JavaScript forms, you will return false on the onSubmit attribute to disable the default refresh after calling the root of the server. But in React, you use the even property you get as a parameter in the onsubmit callback and calling prevent default on it.
Writing it simply looks like this;
const handleSubmit = (e) => {
e.preventDefault();
console.log("Form submitted!");
}
(P.S., The above is a very summarized version of some important things I've learnt about React Forms. There is a world of information not inclusive in this article
P.P.S., You are very welcome to ask questions and make suggestions, observations, and corrections. I am open to learning and answering questions. Also, you can contribute and answer quetions too if you know the answers! Thank you.)