Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple editable field with ReactJS and ES2015
### Try it out with JSBin
(JSBin)[http://jsbin.com/dijefajalo/edit?html,js,console,output]
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.hidden { display:none; }
</style>
<script src="//fb.me/react-0.13.1.js"></script>
<meta charset="utf-8">
<title>React Hello World w/ JSBin</title>
</head>
<body>
<div id="editableField"></div>
</body>
</html>
class EditableListElement extends React.Component {
constructor(props) {
super();
this.ESCAPE_KEY = 27;
this.ENTER_KEY = 13;
this.state = {
editText: props.name,
editing: false
};
}
handleEdit (e) {
return (e) => this.setState({
editing: !this.state.editing
});
}
handleChange (e) {
this.setState({editText: e.target.value});
}
handleSubmit (e) {
var val = this.state.editText.trim();
if (val) {
this.setState({
editText: val,
editing: false,
});
}
}
handleKeyDown (e) {
if (event.which === this.ESCAPE_KEY) {
this.setState({
editText: this.props.name,
editing: false
});
} else if (event.which === this.ENTER_KEY) {
this.handleSubmit(e);
}
}
render() {
return (
<li>
<label className={this.state.editing ? 'hidden' : ''} onDoubleClick={this.handleEdit()}>{this.state.editText}</label>
<input
className={this.state.editing ? '' : 'hidden'}
value={this.state.editText}
onChange={this.handleChange.bind(this)}
onBlur={this.handleSubmit.bind(this)}
onKeyDown={this.handleKeyDown.bind(this)}
/>
</li>
);
}
}
React.render(
<EditableListElement name="Pencil Investments"/>,
document.getElementById('editableField')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.