React Forms and Controlled Component : input, select - part 9

React Forms - Create a form in React using Controlled Component | elpeeda.net


We already mastered using React's State Hook and handling events; now we can advance and work with form submission and controlled inputs. We practiced using stateful components and learned all the fundamental React ideas that are crucial for building applications.

Now, in this article, we'll put all the sections to use, build a form, style the forms that we have already learned how to style components, and use different events - onControl and onSubmit, and so on.

React Form UI

We were creating layouts and output lists of user detail information; going forward, we will accept new user submissions via a form and collect all necessary data.

The form elements contain different types of input elements; in HTML, we access the elements, update the input's respective value, and submit it; in React, it controls the input values, which is why we call them controlled components. You are aware that React is all about components.

In React, the default behavior is avoided, data is saved in a state, and changes are managed by including event handlers.

Let's add another subfolder called 'NewUser' to the components folder and add a file called 'UserForm.js' to it. Create an anonymous function within that file and import it into the App component.

📁components
 📂NewUser
   UserForm.js
    const UserForm = () => {
	  return <form></form>
	}
	export default UserForm
App.js
import UserForm from './Components/NewUser/UserForm'
 const App = () => {
  return <userform />
 }

Here, we are creating an HTML form for user input with <form> element. The form logic can also be placed in a new file, which you can import into UserForm.js. Next, create now three input fields: Name, Level, and Language, and lastly we will add a button to submit the form, for submission of the input data to a form handler.

UserForm.js
const UserForm = () => {
 return <form>
  <div class="user-form">
   <div class="form-control">
    <label>Name</label>
    <input type="text" />
   </div>
   <div class="form-control">
    <label>Language</label>
    <input type="text" />
   </div>
   <div class="form-control">
    <label>Level</label>
    <input type="text" />
   </div>
  </div>
  <div class="form-control">
   <button type="submit">Submit</button>
  </div>
 </form>
}
export default UserForm

Form Handling

The value of an input element may change in response to user input, and whenever a change occurs in an input field, the onChange event is fired.

When the state is updated, we update the value using the useState Hook in the onChange handler and, when the element is to be rendered on the screen, we assign the new state as a value.

React has access to the component state, which displays the most recent values for each form element and provides object support for data submission.

Let's go through this statement line by line.

The state must be set in order to control the input value; the default value is an empty string. Additionally, the input field's value will be stored so that it can be updated later. At the top of the component, don't forget to import useState Hook.

const [name, setName] = useState('');

Next, set the value attribute to access the fields to set and update form data, React control the input value directly.

<input type="text" value={name}>

But now, when you try to type in the input field, you'll discover that you can't. Here comes onChange event handler, it will retrieve and store each value entered by the user. To collect user input, you must create it, listen for changes or key presses, and assign a handler named nameChangeHandler, which will be called when the user types something into the input field. In JSX, we add this event to the element as a prop for all input types.

<input type="text" value={name} onChange={nameChangeHandler}>

When the event is assigned, we must then execute the function when it happens. By default, when we assign the function to an event as a value, we receive the event object, which explains the nature of that event. We called the updating function "setName()" inside of that function and passed an argument.

const nameChangeHandler = (e) => {
 setName(e.target.value);
}
<input type="text" value={setName} onChange={nameChangeHandler}>

As we pass an object 'e', we can get the value of the input element with e.target.value, so whenever the value changes, it is captured. Now, on the browser, the value of the input field changes, and those steps are referred to as controlled components. The react state is the only source of truth.

React Select  onchange

Create the "select" element, giving each "option" a different value, and add the "levelChangeHandler" function to the onChange event handler. The level drop-down list is created by the <select> element. We also added a value attribute to the root select element in React so that we could update it all at once. The value attribute is added to the root "select" tag to specify the selected value.

const [level, setLevel] = useState("Beginner");

const levelChangeHandler = (e) => {
 setLevel(e.target.value)
}

<select value={level} onChange={levelChangeHandler}>
 <option value="beginner">Beginner</option>
 <option value="medium">Medium</option>
 <option value="advance">Advance</option>
</select>

Now that we are familiar with how React's form handling works, we can store the value and listen to change events for additional input fields. Create a file called UserForm.css in the NewForm subfolder, then import it at the beginning of the UserForm component.

-------- UserForm.js ---------
import { useState } from 'react';
import './UserForm.css'

const UserForm = () => {
 const [name, setName] = useState('')
 const [language, setLanguage] = useState('')
 const [level, setLevel] = useState('Begginer')

 const nameChangeHandler = (e) => {
  setName(e.target.value);
 }
 const languageChangeHandler = (e) => {
  setLanguage(e.target.value);
 }
 const levelChangeHandler = (e) => {
  setLevel(e.target.value)
 }
 return <form>
  <div className="form-control">
    <label for="name">Name</label>
    <input id="name" type="text" value={name} onChange={nameChangeHandler} />
   </div>
   <div className="form-control">
    <label for="language">Language</label>
    <input id="language" type="text" value={language} onChange={languageChangeHandler} />
   </div>
   <div className="form-control">
    <label for="level">Choose a Level</label>
    <select id="level" value={levelChangeHandler}>
      <option value="begginer">Begginer>/option>
      <option value="medium">Medium>/option>
      <option value="advance">Advance</option>
    </select>
   </div>
   <div className="form-control">
     <button class="submit-form" type="submit">submit</button>
    </div>
  </form>
}
export default UserForm;

Including CSS, we are giving our submission form some basic styling.

------- UserForm.css -----
form {
  width: 500px;
  max-width: 100%;
  padding: 1rem;
  margin: 2rem auto;
  text-align: center;
  background-color: lightblue;
}
.submit-form {
  display: inline-block;
  background: steelblue;
  width: 40%;
  margin-left: auto;
}
.form-control {
  margin-bottom: .5rem;
  display: flex;
  justify-content: space-between;
}
.form-control label {
  display: inline-block;
  margin-right: .5rem;
  font-weight: bold;
  text-align: left;
}
.form-control input {
  padding: 0.5rem;
  font-size: 1em;
  border: 1px solid #ccc;
  border-radius: 6px;
  width: 20rem;
  max-width: 100%;
}
.form-control input:focus {
  border: 1px solid steelblue;
  outline: 0;
}
.form-control select {
  padding: 1rem;
  font-size: 1rem;
  border: none;
}
.form-control select:focus {
  border: 1px solid steelblue;
}

React Submit Form Data

We will add submit event on the form element and in React we use 'on' keyword whenever we add events, so when the form is submitted, the 'onSubmit' event is triggered. 

<form onSubmit={}></form>

Now create the function in the functional component to listen to the event and pass this handler as a value to the onSubmit event.

const submitFormHandler = () => {
 
}

<form onSubmit={submitFormHandler}></form>

Normally, when we submit a form, it automatically collects data, sends it to a server for processing, and reloads the page. However, with React, we want to stop that default behavior and instead create our own data.

const submitFormHandler = (e) => {
 e.preventDefault()
}

Now, the form won't be sent to the server. If you recall, there are three input fields, which means that there are three states that must be combined. The data that the user has entered into the form will be retrieved using this. Let us use the object here -

const submitFormHandler = (e) => {
 e.preventDefault()
 const UserDetail = {
  name : name,
  level: level,
  language: language
 }
}

Clear Input Field after Submit

When you look at your form, you'll notice that we've already assigned a variable in the value attribute because we want to reset the form when it's successfully submitted.

When working with forms, we must connect input values and data handling logic. Data binding is the process by which the user interface updates the state and the state updates the user interface. As a result of the controlled component behavior, when the value in the input changes, the onChange event handler is also triggered.

const submitFormHandler = (e) => {
 e.preventDefault()
 const UserDetail = {
  name : name,
  lever: level,
  language: language
 }
 setNameHandler('')
 setLevelHandler('')
 setLanguageHandler('')
}

In many instances, we redirect users by sending their data to Web APIs or other external services, but for the time being, we will alert them to any submitted values.

const submitFormHandler = (e) => {
 e.preventDefault()
 const UserDetail = {
  name : name,
  level: level,
  language: language
 }
 setNameHandler('')
 setLevelHandler('')
 setLanguageHandler('')
 alert(`${name} ${level} ${language}`)
}

Conclusion 

In this React tutorial, we'll create the react form UI and also select the value from the drop-down menu, after that, we will handle the form data using the state hook and in the last when a form is submitted we will clear the input field.

The controlled component involves three simple steps: assigning an HTML element, using a state Hook to update the element value, and then assigning an onChange handler to capture changes in the input field and update the state.


0 Comments:

Post a Comment