프로그래머스 프로그래밍 언어 검색 (5) 추가 기능 구현

김영우·2022년 10월 1일
1
post-thumbnail

(6) 추가 기능 구현

- 입력값 하이라이트

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,
      })
  })
}

Appstate프로퍼티에 currentInput을 추가하고, searchInput에 해당 값을 변경할 수 있는 함수 serCurrentInput을 전달한다. 그리고 AppcurrentInput이 변경될 때마다 suggestioncurrentInput값을 전달해주도록 한다.


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태그로 감싸 하이라이트를 적용시켜준다.

profile
불편한 일들을 개발로 풀어내고 싶은 프론트엔드 개발자입니다!

0개의 댓글