Created
December 30, 2016 17:19
-
-
Save goldhand/b5a31545519df9a083767d9de641089d to your computer and use it in GitHub Desktop.
Compare controlled and uncontrolled components
This file contains hidden or 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
/** | |
* Uncontrolled component | |
* DOM controls state and is source of truth. | |
*/ | |
const EditHeader = ({ | |
style, | |
value, | |
}) => { | |
let elem; | |
return <input type="text" style={style} ref={node => elem = node} defaultValue={value} onChange={() => console.log(elem.value)} />; | |
} | |
/** | |
* Controlled component | |
* React (or redux) controls state. | |
*/ | |
class EditField extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
value: props.value, | |
}; | |
this.handleChange = this.handleChange.bind(this); | |
} | |
handleChange(event) { | |
console.log(event.target.value); | |
this.setState({value: event.target.value}); | |
} | |
render() { | |
const {style} = this.props; | |
const {value} = this.state; | |
return ( | |
<input type="text" style={style} value={value} onChange={this.handleChange} /> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment