I got a homework and I don't know what to do with it. It's pretty simple to do a DRAFT-JS editor that will display autocomplete items. Autocomplete interuptting with keyboard ( not in code ). But I have a problem with changing the state editor. This is a spotless version of the code, please help me.
I tried some draft-js component for autocomplete, but it sucks for my waiting on the keyboard. This is clever solution I think, but I am stucked on this point.
import React, { Component } from 'react';
import './testing.css';
import { Editor, EditorState, ContentState, convertToRaw } from 'draft-js';
export default class Autocomplete extends React.Component {
constructor (props){
super(props);
this.items=[
"Test1",
"Home",
"Gold",
"Miner",
"Team",
"Tenis",
];
this.state = {
suggestions: [],
search: "",
replace: "",
testBool: false,
editorState: EditorState.createEmpty()
};
}
onTextChange = (editorState) => {
var contentState = this.state.editorState.getCurrentContent();
const editorContentRaw = convertToRaw(contentState);//Returning some values equals to bullshit
const value =(editorContentRaw.blocks[0].text);
console.log('editor test: '+ value);//Return value of editor
const values=value.split(" ");//Get values to array
let suggestions = [];
if(value.length > 0){
const regex = new RegExp(`^${value}`, 'i');
suggestions = this.items.sort().filter(v => regex.test(v));
}
this.setState(() => ({suggestions, editorState }));
}
suggestionSelected(value){
this.setState(() => ({
suggestion: [],
}));
}
renderSuggestion (){
const {suggestions} = this.state;
if (suggestions.length === 0){
return null;
}
return(
<ul>
{suggestions.map((item) => <li onClick = {() => this.suggestionSelected(item)}> {item}</li>)}
</ul>
);
}
render() {
return (
<div class="AutoCompleteText">
<Editor onChange={this.onTextChange} editorState={this.state.editorState}/>
{this.renderSuggestion()}
</div>
);
}
}
let trigger=false; //Triger for show/hide suggestions
window.addEventListener("keydown", event => { //event listener for keyboard shortcut
if (event.ctrlKey && event.which === 32) {
trigger = (!trigger); //switching true and false values
}
});
Need to be before main component. I got it.