요구사항 랜덤버튼
- 요구사항 : 검색 페이지 관련 > 랜덤 버튼 추가하기
필수 SearchInput 옆에 버튼을 하나 배치하고, 이 버튼을 클릭할 시 /api/cats/random 을 호출하여 화면에 뿌리는 기능을 추가합니다. 버튼의 이름은 마음대로 정합니다.
- 요구사항 이외 특별히 다른 주문이 없으므로 알아서 판단해서 만들면 된다.
onSearch 메소드를 응용해서 만들면 좋을 듯 + 버튼은 button을 쓰면 될 듯.
//랜덤 버튼
const $randomButton = document.createElement("button");
this.$randomButton = $randomButton;
this.$randomButton.className = 'RandomButton';
this.$randomButton.textContent = '랜덤고양이';
$wrapper.appendChild($randomButton);

.SearchInput {
width: 80%;
font-size: 40px;
padding: 10px 15px;
height: 76px;
}
.RandomButton{
width:20%;
font-size: 20px;
height: 76px;
padding:10px;
vertical-align: top;
cursor: pointer;
}
- 버튼 랜덤 버튼 클릭 이벤트 만들어 메소드 전달.
const TEMPLATE = '<input type="text">';
class SearchInput {
constructor({ $target, onSearch, **onRandomSearch** }) {
//검색 input
//...생략
//랜덤 버튼
const $randomButton = document.createElement("button");
this.$randomButton = $randomButton;
this.$randomButton.className = 'RandomButton';
this.$randomButton.textContent = '랜덤고양이';
$wrapper.appendChild($randomButton);
//랜덤 버튼 클릭
**$randomButton.addEventListener('click', e => {
// onSearch('아'); //클릭시 '아' 라는 검색 결과가 나오는지 확인
onRandomSearch();
});**
console.log("SearchInput created.", this);
}
render() {}
}
this.searchInput = new SearchInput({
$target,
onSearch: keyword => {
//로딩 시작 show
this.Loading.show();
api.fetchCats(keyword).then(({ data }) => {
this.setState(data);
//로딩 끝 hide
this.Loading.hide();
});
},
**onRandomSearch : () => {
console.log('랜덤?')
}**
});
- 랜덤버튼 클릭 API 수정. 버튼을 클릭할 시
/api/cats/random 을 호출 할 수 있도록,
api.js에 새로운 API를 추가한다.
/api/cats/random 이 호출이 안되서 */api/cats/random50 으로 변경했음.*
const API_ENDPOINT =
"<http://localhost:4001>";
const api = {
fetchCats: keyword => {
return fetch(`${API_ENDPOINT}/api/cats/search?q=${keyword}`).then(res =>
res.json()
);
},
**fetchRandomCats : () => {
return fetch(`${API_ENDPOINT}/api/cats/random`).then(res =>
res.json()
);
}**
};
- SearchInput.js : 버튼 클릭 →
App.js :
onRandomSearch() 함수 실행 →
apt.js : api 호출(fetch) →
App.js : this.setState(data) →
searchResult.js : data 전달. 화면 그림.
- App.js
- SearchInput.js