Skip to content

Instantly share code, notes, and snippets.

@abinavseelan
Last active March 8, 2018 19:15
Show Gist options
  • Save abinavseelan/ce5ca4fcc3d4c2a259346803ebc2c8f3 to your computer and use it in GitHub Desktop.
Save abinavseelan/ce5ca4fcc3d4c2a259346803ebc2c8f3 to your computer and use it in GitHub Desktop.
(11) Github-style user suggestions using react-input-trigger
...
class App extends Component {
constructor() {
this.state = {
...
startPosition: null,
...
}
...
this.handleTextareaInput = this.handleTextareaInput.bind(this);
}
toggleSuggestor(metaInformation) {
const { hookType, cursor } = metaInformation;
if (hookType === 'start') {
this.setState({
...
startPosition: cursor.selectionStart,
});
}
if (hookType === 'cancel') {
this.setState({
...
startPosition: null,
});
}
}
...
handleKeyDown(event) {
const { which } = event;
const { currentSelection, users } = this.state;
if (which === 40 ) { // 40 is the character code of the down arrow
...
}
if (which === 13) { // 13 is the character code for enter
event.preventDefault();
const { users, currentSelection, startPosition, textareaValue } = this.state;
const user = users[currentSelection];
const newText = `${textareaValue.slice(0, startPosition - 1)}${user}${textareaValue.slice(startPosition + user.length, textareaValue.length)}`
// reset the state and set new text
this.setState({
showSuggestor: false,
left: null,
top: null,
text: null,
startPosition: null,
textareaValue: newText,
});
this.endHandler();
}
}
handleTextareaInput(event) {
const { value } = event.target;
this.setState({
textareaValue: value,
})
}
render() {
return (
<div
style={{
position: 'relative'
}}
onKeyDown={this.handleKeyDown}
>
<InputTrigger
trigger={{
keyCode: 50,
shiftKey: true,
}}
onStart={(metaData) => { this.toggleSuggestor(metaData); }}
onCancel={(metaData) => { this.toggleSuggestor(metaData); }}
onType={(metaData) => { this.handleInput(metaData); }}
endTrigger={(endHandler) => { this.endHandler = endHandler; }}
>
<textarea
style={{
height: '100px',
width: '400px',
lineHeight: '1em',
}}
onChange={this.handleTextareaInput}
value={this.state.textareaValue}
/>
</InputTrigger>
<div
id="dropdown"
style={{
...
}}
>
...
</div>
</div>
);
}
}
render(<App/>, document.getElementById('app'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment