Last active
December 15, 2020 12:39
-
-
Save siakaramalegos/34eac1cfbf4a01c29f9bf19a6c4fae68 to your computer and use it in GitHub Desktop.
Controlled vs Uncontrolled/Serialized Forms in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {Component} from 'react' | |
import serialize from 'form-serialize' | |
export class FrontEndPartyControlled extends Component { | |
static defaultProps = { | |
name: '', | |
spiritAnimal: '', | |
} | |
constructor(props) { | |
super(props) | |
this.state = { | |
name: props.name, | |
spiritAnimal: props.spiritAnimal, | |
} | |
} | |
onChange = (e) => { | |
this.setState({ | |
[e.target.name]: e.target.value, | |
}) | |
} | |
onSubmit = (e) => { | |
e.preventDefault() | |
console.log('submitted!', this.state) | |
} | |
render() { | |
console.log('render!') | |
return ( | |
<div className="ContentWrapper"> | |
<div className="Content"> | |
<h1>Controlled Inputs Example</h1> | |
<form onSubmit={this.onSubmit}> | |
<label> | |
<span className="LabelText">Name</span> | |
<input | |
name="name" | |
type="text" | |
value={this.state.name} | |
onChange={this.onChange} /> | |
</label> | |
<label> | |
<span className="LabelText">Spirit Animal</span> | |
<input | |
name="spiritAnimal" | |
type="text" | |
value={this.state.spiritAnimal} | |
onChange={this.onChange} /> | |
</label> | |
<button className="Button expanded">Submit</button> | |
</form> | |
</div> | |
</div> | |
) | |
} | |
} | |
export class FrontEndPartyUncontrolled extends Component { | |
static defaultProps = { | |
name: '', | |
spiritAnimal: '', | |
} | |
onSubmit = (e) => { | |
e.preventDefault() | |
const form = e.currentTarget | |
const body = serialize(form, {hash: true, empty: true}) | |
console.log('submitted!', body) | |
} | |
render() { | |
console.log('render!') | |
const {name, spiritAnimal} = this.props | |
return ( | |
<div className="ContentWrapper"> | |
<div className="Content"> | |
<h1>Uncontrolled Inputs Example</h1> | |
<form onSubmit={this.onSubmit}> | |
<label> | |
<span className="LabelText">Name</span> | |
<input | |
name="name" | |
type="text" | |
defaultValue={name} /> | |
</label> | |
<label> | |
<span className="LabelText">Spirit Animal</span> | |
<input | |
name="spiritAnimal" | |
type="text" | |
defaultValue={spiritAnimal} /> | |
</label> | |
<button className="Button expanded">Submit</button> | |
</form> | |
</div> | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment