Skip to content

Instantly share code, notes, and snippets.

@goldhand
Created December 30, 2016 17:19
Show Gist options
  • Save goldhand/b5a31545519df9a083767d9de641089d to your computer and use it in GitHub Desktop.
Save goldhand/b5a31545519df9a083767d9de641089d to your computer and use it in GitHub Desktop.
Compare controlled and uncontrolled components
/**
* 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