Monday, December 5, 2022

Controlled and Uncontrolled components in react

 Controlled and Uncontrolled

 components in react






In this article we will learn about controlled and uncontrolled components in react js


Controlled component react js

In react component in which we manage our input fields via react state this component known as react controlled component.


Uncontrolled components react js

The react component that have input filed and its input field should not be controlled with react js state, input filed may be controlling  with direct JavaScript or with refs. This is bit like as traditional JavaScript but main thing is that fields will be not be controlled via React js State. These Component directly handle through DOM.


Note:

  • Both controlled and uncontrolled components  can be used in class component and in  functional component.
  • If someone talk with you about react controlled or uncontrolled component. it's 100%  that here will be at least one input filed  in that component


Controlled Component Example




import React,{useStatefrom 'react'

export default function Teacher() {
   const[name,setName] = useState()
   const[subject,setSubject] = useState()
    const submitHandler = (e) =>{
        e.preventDefault()
        console.log("Name : ",name)
        console.log("Subject : ",subject)

    }
    return (
  <div className = "text-center">
    <h1>Controlled Component</h1>
      <form onSubmit = {submitHandler}>
        <input  type = "text" onChange = {e => setName(e.target.value)}      placeholder = "Name"/>
         <input   type = "text"  onChange = { e => setSubject(e.target.value)}  placeholder = "Subject"/>

          <input  type = "submit"  value = "Submit"/>

      </form>
  </div>
    )
}






Uncontrolled Component Example



import React,{useReffrom 'react'

export default function Student() {
    let name = useRef(null)
    let subject = useRef(null)
    const submitHandler = (e) =>{
        e.preventDefault()
        console.log("Name : ",name.current.value)
        console.log("Subject : ",subject.current.value)

    }
    return (
  <div className="text-center">
    <h1>UnControlled Component</h1>
     <form onSubmit = {submitHandler}>
       <input 
type = "text" 
ref = {name}  
placeholder = "Name"/>
        
        <input  
type = "text" 
ref = {subject}
placeholder = "Subject"/>         
         <input  type = "submit"  value = "Submit"/>
     </form>
  </div>
    )
}



Thanks.

Previous Post
Next Post

post written by:

1 comment:

  1. Good read !

    Summary: Controlled/unControlled components are related to input fields. And if we are dealing with input field value with "state" then it is Controlled component, otherwise it is unControlled component.

    ReplyDelete