Skip to content

Instantly share code, notes, and snippets.

@ernestofreyreg
Last active July 19, 2017 06:10
Show Gist options
  • Save ernestofreyreg/c34c58b45766803e410bdb6c900743ea to your computer and use it in GitHub Desktop.
Save ernestofreyreg/c34c58b45766803e410bdb6c900743ea to your computer and use it in GitHub Desktop.
import React from 'react'
import PropTypes from 'prop-types'
class EditableCell extends React.Component {
constructor (props, context) {
super(props, context)
this.state = {
changedValue: null,
editing: false
}
}
static propTypes = {
value: PropTypes.string.isRequired,
modifyValue: PropTypes.func.isRequired
}
changeValue = ev => {
this.setState({changedValue: ev.target.value})
}
checkEndChanging = ev => {
if (ev.key === 'Enter') {
this.setState(
{editing: false},
() => {
this.props.modifyValue(this.state.changedValue)
}
)
}
}
startEditing = () => {
this.setState({editing: true, changedValue: this.props.value})
}
render () {
const { editing, changedValue } = this.state
const { value } = this.props
return (
<div className='EditableCell'>
{editing
? (
<input
type='text'
value={changedValue}
onChange={this.changeValue}
onKeyPress={this.checkEndChanging}
autoFocus
/>
)
: <div className='value' onClick={this.startEditing}>{value}</div>
}
</div>
)
}
}
export default EditableCell
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment