Last active
December 6, 2019 21:23
-
-
Save wgminer/7c598f73b984185442b437fa2626c32e to your computer and use it in GitHub Desktop.
Add markdown list item on enter to textarea
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
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