Skip to content

Instantly share code, notes, and snippets.

@woeye
Last active June 27, 2018 11:48
Show Gist options
  • Save woeye/b50e0f0e6e24a1f8e6a1e6768b81b838 to your computer and use it in GitHub Desktop.
Save woeye/b50e0f0e6e24a1f8e6a1e6768b81b838 to your computer and use it in GitHub Desktop.
PoC for an inline editor in React
import React from "react";
import ReactDOM from "react-dom";
class Editor extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
this.state = {
editMode: false,
value: "hello world"
};
}
componentDidMount() {
var self = this;
document.getElementById("root").addEventListener("click", function(e) {
if (self.inputRef && self.inputRef.current !== e.target) {
self.setState({ editMode: false });
}
}, { capture: true });
}
handleClick = () => {
this.setState({
editMode: !this.state.editMode
});
};
handleChange = e => {
this.setState({
value: e.target.value
});
};
handleKeyUp = e => {
if (e.keyCode === 13) {
this.setState({
editMode: false
});
}
}
render() {
const value = this.state.value;
return (
<div>
{this.state.editMode && (
<input
ref={this.inputRef}
type="text"
value={value}
onChange={this.handleChange}
onKeyUp={this.handleKeyUp}
autoFocus={true}
/>
)}
{!this.state.editMode && (
<span onClick={e => this.handleClick(e)}>{value}</span>
)}
</div>
);
}
}
export default Editor;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment