ReactJs Unit - III
ReactJs Unit - III
● Checkbox
● Button
● Radio
● TextField
● Select
● Button Group
● Radio Group
● Controlled components rely on React state to manage the form data, while
● uncontrolled components use the DOM itself to handle form data.
● In a controlled component, form data is handled by a React component.
● The alternative is uncontrolled components, where form data is handled
by the DOM itself.
The component is under control of the Components are under the control of
component’s state. DOM.
These components are predictable as are Are Uncontrolled because during the
controlled by the state of the component. life cycle methods the data may loss
It accepts the current value as props We access the values using refs
Have better control on the form data and Has very limited control over form
values values and data
● You can control the submit action by adding an event handler in the
onSubmit attribute for the <form>.
Example -
function MyForm() {
const [name, setName] = useState("");
return (
<form onSubmit={handleSubmit}>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<input type="submit" />
</form>
)
}
❖ Validation
● Validation is the process of verifying user input.
● Validation is required to ensure that contractionary and unauthorized data is not
get stored into database.
● Validation can be handled manually or by using pre-defined library functions and
properties.
● Formik supports synchronous and asynchronous validations.
● Formik handles validation at 2 levels
○ Formstate validation / Form-level validation
○ Inputstate validation / Field-level validation
● “Yup” is used for Schema based validation.
● Formik uses various methods/events for validating the values
○ After Change events/methods
■ handleChange
■ setFieldValue
■ setValues
■ After Blur events/methods
● handleBlur
● setTouched
● setFieldTouched
■ After Submit events/methods
● handleSubmit
● submitForm
Ex:
import React from 'react';
import ReactDOM from 'react-dom';
import {useFormik} from 'formik';
const validateProduct = productData => {
const errors = {}
if(!productData.Name) {
errors.Name = 'Product Name Required';
} else if(productData.Name.length<4) {
errors.Name = 'Name too short..Min 4 required';
}
if(!productData.Price) {
errors.Price = 'Product Price Required';
}
if(!productData.Code) {
errors.Code = 'Product Code Required';
} else if (!/[A-Z]{3}[0-9]{2}/.test(productData.Code)) {
errors.Code = 'Invalid Code..';
}
return errors;
}
const RegisterProductComponent = () => {
const formik = useFormik({
initialValues: {
Name: '',
Price: '',
Code: ''
},
validate: validateProduct,
onSubmit: values => {
alert(JSON.stringify(values));
}
})
return(
<div>
<h2>Register Product</h2>
<form onSubmit={formik.handleSubmit}>
<div className="form-group">
<label>Name</label>
<div>
<input name="Name" onBlur={formik.handleBlur}
onChange={formik.handleChange} value={formik.values.Name}
type="text" />
<div className="text-danger"> {(formik.touched.Name &&
formik.errors.Name)?formik.errors.Name:null} </div>
</div>
</div>
<div className="form-group">
<label>Price</label>
<div>
<input type="text" onBlur={formik.handleBlur}
onChange={formik.handleChange} name="Price"
value={formik.values.Price} />
<div className="text-danger"> {(formik.touched.Price &&
formik.errors.Price)?formik.errors.Price:null} </div>
</div>
</div>
<div class="form-group">
<label>Code</label> <div>
<input onBlur={formik.handleBlur} onChange={formik.handleChange}
name="Code" value={formik.values.Code} type="text" />
<div className="text-danger"> {(formik.touched.Code &&
formik.errors.Code)?formik.errors.Code:null} </div>
</div>
</div>
<div className="form-group">
<button>Register</button>
</div>
</form>
</div>
)
}
ReactDOM.render(
<RegisterProductComponent />,
document.getElementById("root")
);
export default RegisterProductComponent;
❖ writing Styles
● Styles provide attributes to make HTML more interactive and
responsive.
● Styles can be configured using
○ Inline Styles
○ Embedded Styles
○ Cascading Style Sheets (CSS)
○ Styling Libraries [Radium, React Materials]
Inline Styles
● Styles are defined for every element in component individually by
using “style” prop.
● You can pass any dynamic value into “style” attribute so that it can
change dynamically according to state and situation.
● Ex: JavaScript
<div id=”container” style=”background-color:red”>
document.getElementById(“container”).style.backgrou ndColor = “red”;
● React JS also uses “camel case” for configuring the styles
dynamically.
● Dynamic styles are defined by using a style object.
<div style={styleObject}</div>
<div style={{attribute:value,attribute:value}}></div>
Embedded Styles
Index.html
<style>
dt {
background-color: gray;
color:white;
padding:5px;
}
</style>
CSS
Syntax:
app.css
selector {
attribute: value
}
app.js
import “./app.css”
● If you are not using a modular system then you
have to link all your CSS files into index.html
<link rel=”stylesheet” href=”../src/app.css”>
❖ Animations overview
● React Spring. React Spring is an animation library that uses spring physics to
create smooth animations for all types of UI. …
● React Motion. React Motion is a popular open-source animation library for React
that simplifies the process of creating realistic animations. …
● Animations in ReactJS can improve the user experience and make an application
more engaging and interactive. They can be used to:
● Provide feedback for user actions
● Guide users' attention
● Maintain continuity when changing views
● Make the application more intuitive
● Show the loading status of a component
● Transition between routes
● Confirm form submission
Here are some ways to create animations in ReactJS:
❖ Event
What is Event?
● Event is a message sent by sender to its subscriber in order to notify the change.
● Event follows “Observer”, which is a communication design pattern.
● Event uses “Delegate mechanism” – Function Pointer.
❖ Event Binding
Ex: Constructor
App.js
class Product extends React.Component
{
constructor(props){
super(props);
this.state = {
msg : 'Select Database Operation'
}
this.InsertClick = this.InsertClick.bind(this);
}
InsertClick(){
this.setState({
msg: 'Record Inserted'
})
}
render(){
return(
<>
<div className="btn-group">
<button onClick={this.InsertClick} className="btn
btn-primary">Insert</button>
</div>
<h2 className="text-center">{this.state.msg}</h2>
</>
)
}
}
class MainContent extends React.Component
{
render(){
return (
<div className="container-fluid">
<h3>Event Handling</h3>
<Product />
</div>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Ex: DOM Event Handler
App.js
class Product extends React.Component
{
constructor(props){
super(props);
this.state = {
msg : 'Select Database Operation'
}
}
InsertClick(){
this.setState({
msg: 'Record Inserted'
})
}
render(){
return(
<>
<div className="btn-group">
<button onClick={this.InsertClick.bind(this)}
className="btn btn-primary">Insert</button>
</div>
<h2 className="text-center">{this.state.msg}</h2>
</>
)
}
}
class MainContent extends React.Component
{
render(){
return (
<div className="container-fluid">
<h3>Event Handling</h3>
<Product />
</div>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Ex: Without bind() method
class Product extends React.Component
{
constructor(props){
super(props);
this.state = {
msg : 'Select Database Operation'
}
}
InsertClick(){
this.setState({
msg: 'Record Inserted'
})
}
render(){
return(
<>
<div className="btn-group">
<button onClick={()=> this.InsertClick()}
className="btn btn-primary">Insert</button>
</div>
<h2 className="text-center">{this.state.msg}</h2>
</>
)
}
}
class MainContent extends React.Component
{
render(){
return (
<div className="container-fluid">
<h3>Event Handling</h3>
<Product />
</div>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
❖ Event handler
Ex:
App.js
class Product extends React.Component
{
DataOperations(e){
switch(e.target.value)
{
case "Insert":
alert("Record Inserted");
break;
case "Update":
alert("Record Updated");
break;
case "Delete":
alert("Record Deleted");
break;
}
}
render(){
return(
<div>
<div className="btn-group">
<button name="btnInsert" value="Insert"
onClick={this.DataOperations} className="btn btn
primary">Insert</button>
<button name="btnUpdate" value="Update"
onClick={this.DataOperations} className="btn btn
success">Update</button>
<button name="btnDelete" value="Delete"
onClick={this.DataOperations} className="btn btn
danger">Delete</button>
</div>
<h2 align="center"></h2>
</div>
)
}
}
class MainContent extends React.Component
{
render(){
return (
<div className="container-fluid">
<h3>Event Handling</h3>
<Product />
</div>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
● onClick: Used to handle click events on elements like buttons and links
● onChange: Used to handle input changes, such as typed text or selected option
values
● onSubmit: Used to handle form submissions
● onMouseOver: Used when the mouse pointer moves over an element
● onMouseOut: Used when the mouse pointer moves out of an element
● onKeyDown: A keyboard event
● onKeyPress: A keyboard event
● onFocus: A focus event
● onBlur: A focus event
❖ Key Events
● React uses Keyboard events to handle various interactions with regard to key
code, and key actions.
● onKeyDown Indicates the actions to perform
● on key down
● onKeyUp Indicates actions to perform on
● key up.
● onKeyPress Indicates actions to perform
when user finish a key and uses another key.
Properties:-
● keyCode
● charCode
● shiftKey
● ctrlKey
● which
● key [Return the key used]
❖ Synthetic Event