프로그래머스 프로그래밍 언어 검색 (3) Suggestion 구현

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

(3) Suggestion 구현

- Suggestion.js

export default function Suggestion({target}){
  this.element = document.createElement('ul');
  this.element.className = 'suggestion 스타일 입히는 클래스';
  target.addChild(this.element);
  
  this.state = {
    searchResult: [],
  }

  this.setState = (nextState) => {
    this.state = {
      ...this.state,
      ...nextState
    }
    this.render();
  }
  
  this.render = () => {
    const searchResult = this.state.searchResult;
    if(searchResult.length > 0){
      this.element.innerHTML = `${
      	searchResult.map(item=>`<li>${item}</li>`).join("")
  	  }`;
      this.element.style.display = 'block';
    }
    else{
      this.element.style.display = 'none';
    }
  }    
  
  this.render();
}

App컴포넌트의 state가 변경될 때 SuggestionsetState메서드를 함께 사용하여 searchResult를 변경하고, 해당 메서드가 호출될 때마다 render메서드를 호출하여 화면에 다시 렌더링을 진행한다.

- App.js 추가

export default function App({target}){
  //... 이전 코드
  
  this.setState = (nextState) => {
    this.state = {
      ...this.state,
      ...nextState
    }
    
    suggestion.setState({
      searchResult: this.state.searchResult
    });
  }
  
  const suggestion = new Suggestion({
    target: document.querySelector('Suggestion')
  });
}

App컴포넌트에서는 suggestion객체를 새로 생성한다. 그리고 AppsetState메서드가 사용될 때마다 suggestionsetState메서드를 함께 호출하여 변경된 사항을 suggestion객체에 전달하여 화면에 렌더링 시킨다.

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

0개의 댓글