ReactJS - Forms 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Learning and Knowledge Management

ReactJS

Introduction to forms
Ground Rules
For a successful class, please:
• Arrive on time.
• Turn off cell phones.
• Assist your colleagues; show respect to all individuals regardless of their skill and
knowledge level.
• Do not use class time to surf the net, check e-mail, or use instant messaging.
• Adhere to attendance policy as directed by your local training coordinator.
• Make the most of face-to-face training; ask questions and share your own insights and
expertise.
• Leave the room only during break times or in the event of an emergency.
• Manage expectations for your other responsibilities.

2
Agenda
1 Introduction to React forms

2 How to create forms in React

3 Controlled Component

4 Uncontrolled Component

5 Demo

6 Activity

3
Introduction to Forms
The HTML <form> element represents a document section containing interactive controls for
submitting information.

Inside the Form tag we can contain the Forms Control/Elements

Each element has a capability to store the information as its field Value

Form/Control elements include: buttons, checkboxes, text fields, radio buttons, drop-down
menus, etc

HTML form elements will maintain their own state. And these will allow a user to perform update
whenever it is needed based on the user input
3

4
Introduction to React Forms
In react, forms work in a different way compared to HTML forms

Forms elements such as textbox, textarea etc. does not allow a user to update state directly

Forms is directly tied into the state of you react component that is hosting the form

react component immediately reflected into the state of your react component using forms, so we
can retrieve data from the state

Two types of forms in React


• Controlled Form
• Uncontrolled Form

5
Introduction to React Controlled Forms
React components are also known as controlled components

React components are also responsible to control/manage interactions between form elements and
user inputs

Bind the Form State to the component State

It State has to be modified only using setState()

Single Source of truth

Every state mutation will have an associate handler function

6
Introduction to Forms – Test

Create Formtest component(Formtest.js) and try to modify the


value

import React,{Component} from 'react';


class Formtest extends Component{
render(){
return(
<div>
<h2>Forms Example</h2>
<input type="text" value="some text"/>
<input type="submit" value="Submit" />

</div>
)
}
}
export default Formtest;

7
Introduction to Forms – Test
Output

Try to modify the textbox


value and you will observe
you cannot modify the value
with the waring on Console
3

8
React Form - Explanation
Inside App.js

“customerName” is a
state of a component and
initially it is empty

Event handler are bound


inside the constructor

9
Demo – React Form –Explanation(Cont..)
Inside App.js
The state
“customerName” is
captured here but
initially it is empty. If the
user wants he will
modify it by entering
some data inside the
textbox
The entered data is
captured using
onChange() event and
associated handler
function i.e
“handleChange” is
invoked
Demo – React Form –Explanation(Cont..)
Inside App.js

Using the handler


function the state
“customerName” is
modified inside setState()
Demo – React Form –Explanation(Cont..)
Inside App.js

After textbox is
modified by the user he
will click on submit
button, which will
submit the form.
onSubmit of the form
the handler function i.e
“handleSubmit” is
invoked
Demo – React Form –Explanation(Cont..)
Inside App.js

This will display alert with


customerName entered
inside the textbox
Activity

• Create a Customer
component with First Name,
Last Name Phone and
dropdown list which will
display list of country names

• Give a choice to user to


select the country

• Display the data on Console


when the user will submit
the form
Adding Validation to the Form

Inside CustomerComponent.js

constructor(props){
errors: { Adding Validation for firstname.
firstname: ‘’, This will hold the error after
} validating the field.
}

15
Adding Validation to the Form
Inside CustomerComponent.js

changeFirstName(event){
let errors = this.state.errors;
errors.firstname =
event.target.value.length < 5
Adding the validation criteria
? 'Full Name must be at least 5 characters
long!’
: ‘’;
this.setState({
firstname : event.target.value
})
}

16
Adding Validation to the Form
Inside CustomerComponent.js

<input
type="text"
id="fname"
name="firstname"
placeholder="Add first Name"
onChange={this.changeFirstName} />

{
this.state.errors.firstname.length > 0 Will display the error message if
&& <span className='error’> the defined Criteria Does not
{this.state.errors.firstname}</span> match
}

17
Activity - 1
Insert a Telephone Constraint in the form which
will allow only digits to be entered

18
React Forms – Uncontrolled Components
In the previous example where the form
data is completely controlled by react
component by writing different event
handlers

This may be drawback as program will


become lengthy due to many event handlers

The alternate to this approach is


uncontrolled component

In an uncontrolled component the form data


is controlled/managed by DOM, in this case
we can use “refs” to retrieve form values
from the DOM

19
Demo – Uncontrolled Component
Create new component
Empdata(Empdata.js)

20
Demo – Uncontrolled Component - Explanation
Create new component
UnControlledCustomerComponent

<label htmlFor="fname">Customer First Name</label>


<input type="text" id="fname" name="firstname"
placeholder="Add first Name" ref={this.firstname}/>

<label htmlFor="lname">Customer Last Name</label>


<input type="text" id="lname" name="lastname"
Ref is used here using
placeholder="Add last name" ref={this.lastname}/>
which the textbox can be
referred from the DOM
<label htmlFor="lname">Customer Phone</label>
<input type="text" id="cphone" name="cphone"
placeholder="Add Phone Number" ref={this.cphone}/>

21
Demo – Uncontrolled Component - Explanation
Create new component
Empdata(Empdata.js)

constructor(props) {
super(props);
this.onSubmitData = this.onSubmitData.bind(this);
Will create a reference to
this.firstname = React.createRef();
store the value
this.lastname = React.createRef();
this.cphone = React.createRef();
}

22
Demo – Uncontrolled Component - Explanation
Create new component
Empdata(Empdata.js)

onSubmitData(event){ Accessing the Current


console.log("First Name " + this.firstname.current.value) Value for the Created
console.log("Last Name " + this.lastname.current.value) Reference
console.log("Country Name " + this.country.current.value)
console.log("Phone Number " + this.cphone.current.value)
event.preventDefault();
}

23
Activity - 2

• Create a dropdown list which will display list of country names

24
Demo – Uncontrolled Component
Output

25
Module Summary
Now, you should be able to:
• Understand how forms works in react

• Controlled components

• Uncontrolled components

26
Thank You

27

You might also like