Last active
June 21, 2019 12:26
-
-
Save hanneshapke/4a12dd414a193d5406ea to your computer and use it in GitHub Desktop.
Simple editable field with ReactJS and ES2015
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
### Try it out with JSBin | |
(JSBin)[http://jsbin.com/dijefajalo/edit?html,js,console,output] |
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
<!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> |
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 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