Created
August 2, 2016 00:17
-
-
Save soska/932e1e26dde72289151b9ab927046ab0 to your computer and use it in GitHub Desktop.
An editable div component
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
class EditableValue extends Component{ | |
static defaultProps = { | |
onChange: ()=>{}, | |
type: 'text' | |
}; | |
constructor(props){ | |
super(props); | |
this.state = { | |
editMode: false | |
}; | |
} | |
enterEditMode(){ | |
this.setState({ | |
editMode: true | |
}) | |
} | |
exitEditMode(){ | |
this.setState({ | |
editMode: false | |
}) | |
} | |
componentDidUpdate(){ | |
if (this.state.editMode) { | |
this.input.focus(); | |
} | |
} | |
handleChange(e){ | |
const newValue = e.target.value; | |
if (newValue !== this.props.value) { | |
this.props.onChange(newValue); | |
} | |
} | |
renderContent(){ | |
if (this.state.editMode) { | |
return ( | |
<div className="editable__input"> | |
<input | |
ref={input=>{this.input = input}} | |
type={this.props.type} | |
value={this.props.value} | |
onChange={this.handleChange.bind(this)} | |
onBlur={this.exitEditMode.bind(this)} | |
/> | |
</div> | |
); | |
}else{ | |
return ( | |
<div | |
className="editable__content" | |
onClick={this.enterEditMode.bind(this)} | |
> | |
{this.props.displayValue} | |
</div> | |
); | |
} | |
} | |
render(){ | |
return ( | |
<div className="editable"> | |
{this.renderContent()} | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment