Skip to content

Instantly share code, notes, and snippets.

@sahilpaudel
Last active April 14, 2020 07:32
Show Gist options
  • Save sahilpaudel/73644e8efd578668aa8da2785da2dde8 to your computer and use it in GitHub Desktop.
Save sahilpaudel/73644e8efd578668aa8da2785da2dde8 to your computer and use it in GitHub Desktop.
Controlled and Uncontrolled Input Component
import React from "react";
const FunctionalComponent = props => {
const [email, setEmail] = React.useState('');
const [password, setPassword] = React.useState('');
return (
<form>
<input type="email" name="email" onChange={e => setEmail(e.target.value)}/>
<input type="password" name="password" onChange={e => setPassword(e.target.value)} />
</form>
)
/*
* Above form example is of type uncontrolled component as the input value is not controlled by the state change.
* Although we can see the onChange function, the value entered is set to the state.
*/
return (
<form>
<input type="email" name="email" value={email} onChange={e => setEmail(e.target.value)}/>
<input type="password" name="password" value={password} onChange={e => setPassword(e.target.value)}/>
</form>
)
/*
* Above form example is of type controlled component as the input value is controlled by the state.
* And also we can see the onChange function, the value entered is set to the state.
* What happening here is whatever value is set to the state is also reflected to the input component like a two way binding
* this way the input and state are bind together.
*/
/*
* Also instead of using single line setter for state we can use a function for it.
* For example if you want to alter the input data before setting it to the state say: convert it to encrypt the password
*/
// function handling the action
// every action function has an e props for event
const handlePasswordChange = (e) => {
const encryptedPassword = someEncryptingFunction(e.target.value);
setPassword(encryptedPassword)
}
// the input field code will look like
<form>
<input type="email" name="email" value={email} onChange={e => setEmail(e.target.value)}/>
<input type="password" name="password" value={password} onChange={handlePasswordChange}/>
</form>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment