export default function App({target}){
// ... 이전 코드
this.state = {
searchResult: [],
selectedLanguages: [],
currentInput: "",
}
this.setState = (nextState) => {
this.state = {
...this.state,
...nextState,
}
suggestion.setState({
currentInput: this.currentInput,
})
}
const searchInput = new SearchInput({
target: target,
onChange: (data) => {
this.setState({
...this.state,
searchResult: data,
})
},
setCurrentInput: (input) => {
this.setState({
...this.state,
currentInput: input,
})
})
}
App
의 state
프로퍼티에 currentInput
을 추가하고, searchInput
에 해당 값을 변경할 수 있는 함수 serCurrentInput
을 전달한다. 그리고 App
의 currentInput
이 변경될 때마다 suggestion
에 currentInput
값을 전달해주도록 한다.
export default function SearchInput({target, onChange, setCurrentInput}){
// ... 이전 코드
this.element.addEventListener("keyup",(e)=>{
await Fetch(e.target.value).then((data) => onChange(data));
setCurrentInput(e.target.value);
});
}
App
에서 넘겨받은 setCurrentInput
함수로 현재의 입력값을 App
에 전달한다.
export default function Suggestion({target, currentInput}){
// ... 이전 코드
this.state = {
searchResult: [],
currentInput: "",
}
this.render = () => {
const searchResult = this.state.searchResult;
const regexp = new RegExp(currentInput,"ig");
if(searchResult.length > 0){
this.element.innerHTML = `${
searchResult.map((item)=>{
const language = item.replace(regexp,`<span class="하이라이트 적용 클래스">$&</span>`);
return `<li>${language}</li>`
}).join("")
}`;
this.element.style.display = 'block';
}
else{
this.element.style.display = 'none';
}
}
}
App
에서 전달받은 currentInput
과 현재 렌더링중인 텍스트의 일치하는 부분을 정규표현식과 replace
메서드를 사용하여 span
태그로 감싸 하이라이트를 적용시켜준다.