Skip to content

Instantly share code, notes, and snippets.

@tudorilisoi
Last active January 16, 2019 14:34
Show Gist options
  • Select an option

  • Save tudorilisoi/fd785749fddadab3df246c7c50229db2 to your computer and use it in GitHub Desktop.

Select an option

Save tudorilisoi/fd785749fddadab3df246c7c50229db2 to your computer and use it in GitHub Desktop.
class ControlledInput extends React.Component {
constructor(props) {
super(props)
this.state = { value: props.initialValue || '' }
}
componentDidUpdate(prevProps, prevState) {
console.log(prevProps.initialValue, this.props.initialValue)
if (prevProps.initialValue !== this.props.initialValue) {
this.setState({ value: this.props.initialValue || '' })
}
}
onChange = (ev) => {
const { value } = ev.target
this.setState({
value
}, () => {
if (this.props.onChange) {
this.props.onChange(this.state.value)
}
})
}
render() {
const { initialValue, tag, onChange, ...rest } = this.props
console.log('value', initialValue)
const props = {
...rest,
onChange: this.onChange,
value: this.state.value,
}
return React.createElement(tag, props)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment