Dhananjay Patel Logo
  1. Home
  2. / Blog
  3. / Controlled Vs Uncontrolled
  4. / Lessons
  5. / 2

2. Uncontrolled Component

Uncontrolled Components are the components that are not controlled by the React state and are handled by the DOM (Document Object Model). So in order to access any value that has been entered we take the help of refs.

Lets convert the Controlled component code to Uncontrolled component

App.js
import { useState } from "react"
import { useRef } from "react"
const App = () => {
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const emailRef = useRef()
const passwordRef = useRef()
function onSubmit(e) {
e.preventDefault()
// YOUR SUBMIT CODE GOES HERE
console.log({email, password})
console.log({
email: emailRef.current.value,
password: passwordRef.current.value
})
}
return (
<form onSubmit={onSubmit}>
<label htmlFor="email">Email</label>
<input
value={email}
onChange={e => setEmail(e.target.value)}
ref={emailRef}
type="email"
id="email"
/>
<label htmlFor="password">Password</label>
<input
value={password}
onChange={e => setPassword(e.target.value)}
ref={passwordRef}
type="password"
id="password"
/>
<button type="submit">Submit</button>
</form>
)
}
export default App

Uncontrolled component also have some drawbacks as we have very limited control over its value, and very hard to debug.