42 - React Forms
42 - React Forms
Techno Verse YT
Heavenly Delicious
React Forms REACT
• The form has the default HTML form behavior of browsing to a new
page when the user submits the form.
• If you want this behavior in React, it just works. But in most cases, it’s
convenient to have a JavaScript function that handles the submission
of the form and has access to the data that the user entered into the
form.
• The standard way to achieve this is with a technique called
“controlled components”.
• HTML form elements work a bit differently from other DOM elements
in React, because form elements naturally keep some internal state.
React Forms REACT
• In HTML, form elements typically maintain their own state and update
it according to the user input.
• In the controlled component, the input form element is handled by the
component rather than the DOM.
• Here, the mutable state is kept in the state property and will be updated
only with setState() method.
Controlled Component REACT
• You can control the values of more than one input field by adding a
name attribute to each element.
• We will initialize our state with an empty object.
• To access the fields in the event handler use the event.target.name
and event.target.value syntax.
• To update the state, use square brackets [bracket notation] around
the property name
Multiple Input Fields REACT
• Note: We use the same event handler function for both input fields,
we could write one event handler for each, but this gives us much
cleaner code and is the preferred way in React.