Skip to content

Instantly share code, notes, and snippets.

@wgminer
Last active December 6, 2019 21:23
Show Gist options
  • Save wgminer/7c598f73b984185442b437fa2626c32e to your computer and use it in GitHub Desktop.
Save wgminer/7c598f73b984185442b437fa2626c32e to your computer and use it in GitHub Desktop.
Add markdown list item on enter to textarea
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
text: '- asda'
};
this.myRef = React.createRef();
this.handleChange = this.handleChange.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
}
handleChange(e) {
this.setState({ text: e.target.value });
}
handleKeyDown(e) {
if (e.keyCode === 13) {
let cursorPos = e.target.selectionStart;
let val = e.target.value;
let textBefore = val.substring(0, cursorPos );
let textAfter = val.substring( cursorPos, val.length );
let lineBefore = textBefore.split('\n').pop();
let isMatch = lineBefore.match(/-\s[a-zA-Z]+/g);
if (isMatch != null) {
e.preventDefault();
let newVal = textBefore + '\n- ' + textAfter.trimRight();
this.setState({ text: newVal });
setTimeout(() => {
this.myRef.current.setSelectionRange(cursorPos+3, cursorPos+3);
}, 0);
return false;
}
if (lineBefore == '- ') {
e.preventDefault();
let clipped = textBefore.substring(0, textBefore.length - 3);
let newVal = clipped + '\n\n' + textAfter.trimRight();
this.setState({ text: newVal });
setTimeout(() => {
this.myRef.current.setSelectionRange(cursorPos+3, cursorPos+3);
}, 0);
return false;
}
}
}
render() {
return (
<textarea ref={this.myRef} className="App" value={this.state.text} onChange={this.handleChange} onKeyDown={this.handleKeyDown} />
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment