REACT - Controlled component and uncontrolled component
Controlled component and uncontrolled component
Controlled Component : when an input control is managed by state is called Controlled component
uncontroller component : when an input control is direct managed by java script or jquery i.e reading value of control using getelementbyid.
// Controlled Component SAMPLE
import React,{useState} from "react";
function ControlledComponentUsage()
{
let [StateForInput,setStateForInput] = useState('');
return(
<div>
<input type="text" onChange={(e) => setStateForInput(e.target.value)} ></input>
<p>
value in Input Box : - {StateForInput}
</p>
</div>
)
}
export default ControlledComponentUsage;
// UNCONTROLLED COMPONENT
import React,{useRef} from "react";
function UnControlledComponentUsage()
{
let InputOne = useRef(null);
let InputTwo = useRef(null);
function ReadControlValue(e)
{
e.preventDefault();
console.log(InputOne.current.value)
console.log(InputTwo.current.value)
// Without using Ref. WE can use old value of acccessing the control/elements using id tag
let InputThree = document.getElementById('InputThree').value;
console.log(InputThree)
}a
return(
<form onSubmit={ReadControlValue} >
<div>
<input type="text" ref={InputOne} ></input> <br/><br/>
<input type="text" ref={InputTwo} ></input ><br/><br/>
<input id="InputThree" type="text"></input><br/><br/>
<button type="Submit" >Save</button>
</div>
</form>
)
}
export default UnControlledComponentUsage;
Comments
Post a Comment