Part 19 Controlled way React forms | React | React Forms | Form validations | Error handling смотреть онлайн
Forms:-
-----
- Forms can be handled in 2 ways.
1. Controlled way
2. Uncontrolled way
Controlled way:-
------------------
In React, a controlled component is a form element whose value is controlled by React state. This means that every time the user types something into a form input, the state is updated with the new value, and the component is re-rendered with the new value.
Using controlled components in React ensures that the form data is always in sync with the state, and allows us to add validation and other custom logic to the form.
- using useState() hook and onChange() events , we can implement controlled way.
1. Create one useState hook for each input control.
const [firstName, setFirstName] = useState('');
2. Assign the variable value to the input using the "value" property.
- Handle the onChange event for the input and assign the latest value to input using the setter method.
input value={firstName} onChange={onFirstNameHandler}
- firstName always will have the latest value since it binds with the HTML change event.
It imports useState from the React library and uses it to declare three state variables: username, password, and errors.
There are three functions: handleUsername, handlePassword, and handleSubmitForm which are used to handle the events of changing the input fields of the form and submitting the form.
The handleUsername function is called when the onChange event is triggered on the username input field. It sets the value of the username state variable to the value of the input field.
The handlePassword function is called when the onChange event is triggered on the password input field. It sets the value of the password state variable to the value of the input field.
The handleSubmitForm function is called when the onSubmit event is triggered on the form. It prevents the default behavior of the form and then calls the validate function to validate the form data.
The validate function checks whether the username and password fields are filled in or not, and sets the errors to object accordingly. If there are no errors, it checks whether the entered username and password are correct or not. If they are correct, an alert message is shown indicating a successful login.
The return statement contains the JSX code that defines the login form. It has two input fields for username and password, and a button to submit the form. It also has a link to the registration page.
Conditional rendering is used to display error messages if there are any errors in the username and password fields.
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Part 19 Controlled way React forms | React | React Forms | Form validations | Error handling» бесплатно и без регистрации, вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.