inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

묻고 답해요

176만명의 커뮤니티!! 함께 토론해봐요.

TabBar.js 오류가 자꾸 발생하는데 무슨이유인지 모르겠습니다;;

해결됨

한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지

전체 사진 처음 화면은 로딩 되서 잘나오는데 펭귄이나 다른탭을 클릭하면 아래와 같은 오류가 나오는데 TabBar.js onclick 함수가 아니라는데;; 왜이런건지 함수가 맞는데 아래에 제가 작성한 코드 입니다 검토 좀 부탁드립니다.^^;; TabBar.js export default function TabBar({ $app, initialState, onClick }) { // TabBar 클래스를 생성합니다. 초기값과 클릭 이벤트를 받습니다. this.state = initialState; // 초기값 설정 this.onClick = onClick; // 클릭 이벤트 설정 this.$target = document.createElement("div"); // 새로운 div 요소를 생성합니다. this.$target.className = "tab-bar"; // div 요소에 클래스 이름을 추가합니다. $app.appendChild(this.$target); // $app 요소에 div 요소를 추가합니다. this.template = () => { let temp = `<div id="all">전체</div><div id="penguin">펭귄</div> <div id ="koala">코알라</div><div id ="panda">판다</div>`; // 전체 탭을 추가합니다. return temp; // temp를 반환합니다. }; this.render = () => { // 렌더링 함수 this.$target.innerHTML = this.template(); // div 요소의 innerHTML을 template 함수의 반환값으로 설정합니다. let $currentTab = document.getElementById(this.state); // 현재 탭을 선택합니다. // $currentTab ? ($currentTab.className = "clicked") : ""; // 현재 탭이 존재하면 clicked 클래스를 추가합니다. 없으면 변화없음. $currentTab && ($currentTab.className = "clicked"); // && 연산자를 사용하여 현재 탭이 존재하면 clicked 클래스를 추가합니다. const $tabBar = this.$target.querySelectorAll("div"); // 모든 div 요소를 tabBar 요소에 담아온다. $tabBar.forEach((elm) => { elm.addEventListener("click", () => { // 각 div 요소에 클릭 이벤트 리스너를 추가합니다. this.onClick(elm.id); // 클릭한 div 요소의 id를 onClick 함수에 전달합니다. }); }); }; this.setState = (newState) => { // state를 변경하는 함수 this.state = newState; // state를 새로 받은 newState로 업데이트합니다. this.render(); // state가 변경되면 렌더링 함수를 다시 호출하여 화면을 업데이트합니다. }; this.render(); // 렌더링 함수를 호출합니다. } App.js import TabBar from "./components/TabBar.js"; // TabBar.js 파일을 불러옵니다. import Content from "./components/Content.js"; // Content.js 파일을 불러옵니다. import { request } from "./components/api.js"; // api.js 파일을 불러옵니다. export default function App($app) { // App 생성자 함수를 생성합니다. // $app은 App 컴포넌트가 렌더링될 DOM 요소입니다. this.state = { //state 초기값 설정 currentTab: "all", // 탭 초기값 설정 tabbar 컴포넌트에 전달할 현재 탭 데이터 photos: [], // 사진 초기값 설정 content 컴포넌트에 전달할 사진 데이터 }; const tabbar = new TabBar({ $app, // App 컴포넌트가 렌더링될 DOM 요소를 전달합니다. initialState: "", // 초기값 설정 oncClick: async (name) => { // 클릭 이벤트 설정 변경값을 currentTab에 저장 this.setState({ // 클릭한 탭의 데이터를 state에 저장합니다. ...this.State, // 기존 state를 복사합니다. 스프레드 연산자 currentTab: name, // 클릭한 탭의 이름을 currentTab에 저장합니다. photos: await request(name === "all" ? "" : name), // 클릭한 탭의 새로운 사진을 request 이름으로 함수를 불러와 저장합니다. // request 함수는 비동기 함수로 async await를 사용하여 데이터를 받아옵니다. }); }, }); const content = new Content({ $app, // App 컴포넌트가 렌더링될 DOM 요소를 전달합니다. initialState: [], // 초기값 설정 }); this.setState = (newState) => { // 업데이트 값을 newState로 받습니다. this.state = newState; // state를 새로 받은 newState로 업데이트합니다. tabbar.setState(this.state.currentTab); // tabbar 컴포넌트에 state를 전달합니다. content.setState(this.state.photos); // content 컴포넌트에 state를 전달합니다. }; const init = async () => { //웹페이지가 로드되면 실행되는 함수 try { const initialPhotos = await request(); // request 함수를 불러와 initialPhotos에 저장합니다. this.setState({ // state를 initialPhotos로 업데이트합니다. ...this.state, // 기존 state를 복사합니다. 스프레드 연산자 photos: initialPhotos, // initialPhotos를 photos에 저장합니다. }); } catch (err) { console.log(err); } }; init(); // 웹애플리케이션이 실행될때 init 함수를 실행합니다. } index.js import App from "../src/App.js"; const $app = document.getElementById("app"); new App($app); api.js const API_URL = "https://animal-api-two.vercel.app"; // 이미지 url을 변수에 저장 // const $content = document.querySelector("div.content"); //(api 불러오는 코드만 남겨놓기 위해 삭제제) // let template = []; // (api 불러오는 코드만 남겨놓기 위해 삭제제) //API export const request = async (name) => { const res = await fetch(name ? `${API_URL}/${name}` : API_URL); // fetch 함수를 사용하여 API_URL을 호출합니다. name이 있으면 name을 호출합니다. 없으면 API_URL을 호출합니다. try { if (res) { let data = await res.json(); return data.photos; } } catch (err) { console.log(err); } }; index.html <!DOCTYPE html> <head> <title>Animal Album</title> <meta charset="UTF-8" /> <link rel="stylesheet" href="../project2/src/style.css" /> <script type="module" src="../project2/src/index.js" defer></script> </head> <body> <div id="app"> <!-- TAB BAR --> <!-- CONTENT --> </div> </body> content.js export default function Content({ $app, initialState }) { this.state = initialState; this.$target = document.createElement("div"); this.$target.className = "Content"; $app.appendChild(this.$target); this.template = () => { let temp = []; if (this.state) { this.state.forEach((elm) => { temp += `<img src="${elm.url}"></img>`; }); } return temp; }; this.render = () => { this.$target.innerHTML = this.template(); }; this.setState = (newState) => { this.state = newState; this.render(); }; this.render(); } 콘솔 오류코드 TabBar.js:26 Uncaught TypeError: this.onClick is not a function at HTMLDivElement.<anonymous> (TabBar.js:26:14)

  • javascript
  • rest-api
  • spa
  • dom
musful 댓글 2 좋아요 0 조회수 240

Header에서 정렬기준

해결됨

한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지

Header에서 total, cost, fun 등 정렬 값이 바뀌는 건 알겠는데, 이 값이 바뀔 때 점수가 높은순으로 정렬이 되는데, 이 정렬을 지정해주는 실행 코드가 어디에 있는지 모르겠어요. <div class="filter"> <select id="sortList" class="sort-list"> <option value="total" ${sortBy === 'total' ? 'selected' : ''}>Total</option> <option value="cost" ${sortBy === 'cost' ? 'selected' : ''}>Cost</option> <option value="fun" ${sortBy === 'fun' ? 'selected' : ''}>Fun</option> <option value="safety" ${sortBy === 'safety' ? 'selected' : ''}>Safety</option> <option value="internet" ${sortBy === 'internet' ? 'selected' : ''}>Internet</option> <option value="air" ${sortBy === 'air' ? 'selected' : ''}>Air Quality</option> <option value="food" ${sortBy === 'food' ? 'selected' : ''}>Food</option> </select> </div>

  • javascript
  • rest-api
  • spa
  • dom
김수현 댓글 2 좋아요 1 조회수 156

2-3 동물 사진 request 오류

해결됨

한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지

안녕하세요 코드 궁금증은 아니구요 이렇게 request로 이미지 불러오기를 했을 때 이미지를 불러오긴 하는거 같은데 GET http://127.0.0.1:5500/undefined 404 (Not Found) 와 같은 오류가 발생하면서 엑박이 뜨거든요... 도저히 제가 어디서 잘못했는지 발견을 못하겠어서 혹시 해결 방법을 아신다면 알려주시면 감사드리겠습니다...

  • javascript
  • rest-api
  • spa
  • dom
먼재 댓글 2 좋아요 1 조회수 176

병령처리 하지만 동기화와 같은 출력값

해결됨

한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지

const workA = () => { return new Promise((resolve) => { setTimeout(() => { resolve(`workA`); }, 5000); }); }; const workB = () => { return new Promise((resolve) => { setTimeout(() => { resolve(`workB`); }, 3000); }); }; const workC = () => { return new Promise((resolve) => { setTimeout(() => { resolve(`workC`); }, 10000); }); }; const start = async () => { try { let results = await Promise.all([workA(), workB(), workC()]); console.log(results); results.forEach((res) => console.log(res)); } catch (err) { console.log(err); } }; [10:01] 강의 내용 보면 workA가 5초 workB가 3초, workC가 10초인데, 결국 출력 되는 값을 보면 동시에 출력이 됩니다. 그리고 순서도 A, B, C 순입니다. let resultA = await workA(); let resultB = await workB(); let resultC = await workC(); console.log(resultA); console.log(resultB); console.log(resultC); 물론 실행시간의 차이는 있지만, 실직적으로 프로그램에 표기 되는 값은 바로 위에 있는 코드예제에서 보여주신 A, B, C랑 같은데, 병령처리라면 시간이 짧은 B가 실행되고 그 다음에 A, 그 다음 C가 아웃풋으로 나와야 하는거 아닌가요??

  • javascript
  • rest-api
  • spa
  • dom
Daniel Yang 댓글 2 좋아요 0 조회수 186

제네릭을 사용하실 때 콤마

해결됨

코어 프런트엔드 UI - Part 2

제네릭을 사용하실 때 콤마는 제네릭과 JSX의 혼동방지 제네릭 구문을 명확히 해서 코드의 가독성 높임 TSX 파일에서 사용할 때 하는 일반적인 관례 로 인한 이유가 맞을까요?

  • react
  • typescript
  • dom
  • ui
  • vanilla-js
oridori2705 댓글 2 좋아요 0 조회수 217

CSSOM 강좌는 언제 올라오나요?

미해결

DOM 기본

- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 안녕하세요. 선생님. 덕분에 재밌게 근본을 다지고 있는데요. 혹시, 세 번째 강좌인 cssom에 대한 강좌는 아직 계획이 없으신걸까요? ㅜㅜ 향후 계획이 있으시다면, 언제 오픈하실 지 궁금합니다. ㅎㅎ 모조록 건강하시고, 새해 복 많이 받으세용 감사합니다.

  • HTML/CSS
  • javascript
  • dom
러닝맨 댓글 1 좋아요 2 조회수 174

6분 53초 질문입니당

해결됨

웹 프론트엔드를 위한 자바스크립트 첫걸음

src파일이랑 index.html파일 만드실 때, 문자 앞에 아이콘이 있는데, 저는 없습니다. 또한 우측 큰 창에 보면 시작, index.js탭은 있는데 html탭이 없네요,,, 또한 test아래 빈공간 우클릭해서 새폴더 만들기로 src생성 후 html을 만들경우 html이 src 상단으로 올라가는데 정상적인 상황인가요...? 뭔가 설정이 잘못된 건가요...? 스크린샷 파일 첨부 해드립니다 ㅠ

  • javascript
  • dom
ㄱ근 댓글 2 좋아요 1 조회수 166

API 관련 질문

해결됨

한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지

안녕하세요 ! 해당 강의를 듣고 기능은 비슷한데 내용은 조금 다른 홈페이지를 제작해보고 싶어져서 질문 드립니다 ! API를 호출하는 기능은 이해했는데, 강사님이 만드신 API 처럼 저도 직접 간단한 정보를 담은 api 를 만들어보고 싶은데 이 부분은 어떻게 제작하는 지 알 수 있을까요?!

  • javascript
  • rest-api
  • spa
  • dom
지지지지지 댓글 2 좋아요 1 조회수 181

citiList 의 더보기 버튼 함수

해결됨

한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지

안녕하세요 citiList 에 더보기 버튼이 있는데 handleLoadMore 함수가 더보기 버튼을 클릭했을 때 동작하는 함수인 것 이해했습니다. 근데 해당함수는 citiList 컴포넌트에서만 사용하니까 CitiList.js 에 작성할것으로 예상했는데 App.js 에 작성하셔서 App.js 에서 작성하고 CitiList 로 전달하는 이유가 궁금합니다!

  • javascript
  • rest-api
  • spa
  • dom
찹찹이 댓글 1 좋아요 1 조회수 161

input 태그 value문제 해결 방법

해결됨

한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지

초기값이 '' 이여서 강의에서는 value 값을 맨뒤로 넣고 input 태그에 닫힘을 작성하지 않음으로, 동작하게 하였는데 다른 방법으로는 <input type="text" placeholder="Search" id="search" value="${searchWord}" autocomplete="off"/> 로 작성하였습니다, value 를 싱글쿼터나 더블쿼터로 감싼다음 ${} 를 사용하시면, 뒤에다가 다른 속성을 넣거나 닫아도 정상 동작합니다. 참고 하실분 참고하셔도 좋습니다.

  • javascript
  • rest-api
  • spa
  • dom
hollis9797 댓글 1 좋아요 0 조회수 247

9분 30초 || 'all' 영상 누락

해결됨

한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지

혹시나 기본 '/' 경로에서 펭귄눌렀다 popstate 로 뒤로갔을 경우 'clicked' css가 먹지않는 현상, 강의 내용에서 저부분이 영상 짤려서 놓치기 쉬울꺼 같습니다. 저도 강의보면서 하다가 || 'all' 하는 부분 제대로 보기힘들어서 못 적었다가 나중에 문제생겨서 로직 보다가 발견했습니다,

  • javascript
  • rest-api
  • spa
  • dom
hollis9797 댓글 2 좋아요 0 조회수 113

영상보고 직접 api를 구현해봤는데 자꾸 프로젝트를 변경하면 서버가 꺼지;는데 방법이 있을까요

해결됨

한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지

코드 관련 질문은 아래와 같이 '코드블럭' 기능을 이용해주세요! + 오류 메세지도 함께 올려주시면 좋아요 🙂 console.log('hello'); 이런식으로 구축했는데 프로젝트만 바꾸면 서버가 꺼져서요..

  • javascript
  • rest-api
  • spa
  • dom
용우 댓글 2 좋아요 0 조회수 152

경로 질문드립니다

해결됨

한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지

코드 관련 질문은 아래와 같이 '코드블럭' 기능을 이용해주세요! + 오류 메세지도 함께 올려주시면 좋아요 🙂 npm error code ENOENT npm error syscall open npm error path C:\Users\사용자이름\Desktop\animal_album_Main\animal_album-3\package.json npm error errno -4058 npm error enoent ENOENT: no such file or directory, open 'C:\Users\사용자이름\Desktop\animal_album_Main\animal_album-3\package.json' npm error enoent This is related to npm not being able to find a file. npm error enoent npm error A complete log of this run can be found in: C:\Users\사용자이름\AppData\Local\npm-cache\_logs\2024-12-06T08_26_22_967Z-debug-0.log 안녕하세요 질문드립니다 몇일동안 npm init 떄문에 질문드립니다 npm 설치시 해당 프로젝트 파일이 c드라이브 안에만 있어야 되는건가요 ? 1번 바탕화면에 프로젝트가 있을떄도 실행이 안됩니다 2번 c드라이브 -> User -> (사용자이름) -> github-> 해당 폴더 -> 프로젝트 폴더 3번 c드라이브 -> 프로젝트 폴더 3번일때만 되고 1,2번일때는 npm init 설치가 안되는데 2번도 가능하게 할려면 어떻게 해야하는지 궁금합니다

  • javascript
  • rest-api
  • spa
  • dom
서경진 댓글 2 좋아요 0 조회수 174

popover createPortal 방식에서

해결됨

코어 프런트엔드 UI - Part 2

portal할 요소를 아래처럼 작성하고 있는데 <div id="popoverRoot" /> 저는 이거를 popover를 사용하는 개발자가 신경안쓸 수 있도록 하는 방법이 있지않을까 해서 두 가지 방법을 생각했는데 하나는 useLayoutEffect 내부에서 아래와 같은 로직으로 div요소를 만드는 방법하고, useLayoutEffect(() => { if (typeof window !== 'undefined') { const portalElement = document.getElementById(portalId) if (!portalElement) { const newPortalElement = document.createElement('div') newPortalElement.id = portalId document.body.appendChild(newPortalElement) } } }, []) 아니면 document.body로 보내는 방법을 생각했는데 return createPortal( ... , document.body ) 두 방법 중 어느게 적절한지를 잘 모르겠어서.. 혹은 위 방법처럼 했을 때 어떤 문제가 생기는지도 아직 예상이 안되는데 혹시 강사님의 생각은 어떠신지 궁금합니다!

  • react
  • typescript
  • dom
  • ui
  • vanilla-js
oridori2705 댓글 2 좋아요 0 조회수 202

regionList 에 region별 cities가 정상 로딩이 안됩니다.

해결됨

한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지

영상 7:53 부분에 코드를 완성하면, regionList에 있는 region 클릭 시, 영상처럼 region 별로 cities가 나와야 하지만, 아래 에러가 생겨서 정상적으로 로딩이 안됩니다. 혹시 어떤 문제 인지 알려주시면, 너무 고맙습니다. 감사합니다! app.js 코드는 아래와 같이 입력했습니다. import Header from "./components/Header.js"; import RegionList from "./components/RegionList.js"; import CityList from "./components/CityList.js"; import CityDetail from "./components/CityDetail.js"; import { request } from "./components/api.js"; export default function App($app) { const getSortBy = () => { if (window.location.search) { return window.location.search.split("sort=")[1].split("&")[0]; } return "total"; }; const getSearchWord = () => { if (window.location.search && window.location.search.includes("search=")) { return window.location.search.split("search=")[1]; } return ""; }; this.state = { startIdx: 0, sortBy: getSortBy(), searchWord: getSearchWord(), region: "", cities: "", }; const header = new Header({ $app, initialState: { sortBy: this.state.sortBy, searchWord: this.state.searchWord, }, handleSortChange: async (sortBy) => { const pageUrl = `/${this.state.region}?sort=${sortBy}`; history.pushState( null, null, this.state.searchWord ? pageUrl + `&search=${this.state.searchWord}` : pageUrl ); const cities = await request( 0, this.state.region, sortBy, this.state.searchWord ); this.setState({ ...this.state, startIdx: 0, sortBy: sortBy, cities: cities, }); }, handleSearch: async (searchWord) => { history.pushState( null, null, `/${this.state.region}?sort=${this.state.sortBy}&search=${searchWord}` ); const cities = await request( 0, this.state.region, this.state.sortBy, searchWord ); this.setState({ ...this.state, startIdx: 0, searchWord: searchWord, cities: cities, }); }, }); const regionList = new RegionList({ $app, initialState: this.state.region, handleRegion: async (region) => { history.pushState(null, null, `/${region}?sort=total`); const cities = await request(0, region, "total"); this.setState({ ...this.state, startIdx: 0, sortBy: "total", region: region, searchWord: "", cities: cities, }); }, }); const cityList = new CityList({ $app, initialState: this.state.cities, handleLoadMore: async () => { const newStartIdx = this.state.startIdx + 40; const newCities = await request( newStartIdx, this.state.region, this.state.sortBy, this.state.searchWord ); this.setState({ ...this.state, startIdx: newStartIdx, cities: { cities: [...this.state.cities.cities, ...newCities.cities], isEnd: newCities.isEnd, }, }); }, }); const cityDetail = new CityDetail(); this.setState = (newState) => { this.state = newState; cityList.setState(this.state.cities); header.setState({ sortBy: this.state.sortBy, searchWord: this.state.searchWord, }); regionList.setState(this.state.region); }; const init = async () => { const cities = await request( this.state.startIdx, this.state.region, this.state.sortBy, this.state.searchWord ); console.log(cities); this.setState({ ...this.state, cities: cities, }); }; init(); } regionList.js 코드는 아래와 같이 입력했습니다. export default function RegionList({ $app, initialState, handleRegion }) { this.state = initialState; this.$target = document.createElement("div"); this.$target.className = "region-list"; this.handleRegion = handleRegion; $app.appendChild(this.$target); this.template = () => { const regionList = [ "🚀 All", "🌏 Asia", "🕌 Middle-East", "🇪🇺 Europe", "💃 Latin-America", "🐘 Africa", "🏈 North-America", "🏄 Oceania", ]; let temp = ``; regionList.forEach((elm) => { let regionId = elm.split(" ")[1]; temp += `<div id=${regionId}>${elm}</div>`; }); return temp; }; this.render = () => { this.$target.innerHTML = this.template(); if (this.state) { let $currentRegion = document.getElementById(this.state); $currentRegion && ($currentRegion.className = "clicked"); } else { document.getElementById("All").className = "clicked"; } const $regionList = this.$target.querySelectorAll("div"); $regionList.forEach((elm) => { elm.addEventListener("click", () => { this.handleRegion(elm.id); }); }); }; this.setState = (newState) => { this.state = newState; this.render(); }; this.render(); }

  • javascript
  • rest-api
  • spa
  • dom
댓글 2 좋아요 1 조회수 208

[#보일러플레이트 코드 사용법 문의] 강의자료[보일러플레이트] 사용법에 대해서 문의 드려요

해결됨

코어 프런트엔드 UI - Part 1

안녕하세요! 보일러플레이트 코드를 다운받아 npm install 을 하면, route 관련 코드가 작성되어 있고, http://localhost:3000으로 브라우저를 들어가면 좌측 메뉴가 disabled 되어 클릭이 안되는 상태입니다. route 설정 코드가 보일러플레이트 코드에 일부 작성되어 있는데, route 설정 강좌를 시청 해야하는지 혹은 강좌 내용대로 코드를 다시 작성해야하는지 궁금합니다. routes.ts를 보면, children의 값이 null 인 부분이 확인됩니다. 아코디언 강좌를 예로 든다면, 아코디언 컴포넌트를 만들고, 여기 null 인 부분에 값을 넣는거 아닐까 생각이 드는데요 첨부된 보일러플레이트 코드를 어떻게 사용해야하는지 질문 드립니다. 감사합니다! :]

  • react
  • typescript
  • dom
  • ui
  • vanilla-js
프린이 댓글 2 좋아요 0 조회수 360

regionList 클릭시 해당 cities가 안나옵니다.

해결됨

한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지

혼자서 찾아보려고 했는데 도저히 모르겠네요 ㅜ 오류메세지는 나오는건 없고 제목과 같습니다. region을 선택하면 해당 cities가 나와야하는데 안나와요 ㅜ import Header from "./components/Header.js"; import RegionList from "./components/RegionList.js"; import CityDetail from "./components/CityDetail.js"; import CityList from "./components/CityList.js"; import { request } from "./components/api.js"; export default function App($app){ const getSortBy = () => { if (window.location.search){ return window.location.search.split('sort=')[1].split('&')[0]; } return 'total'; }; const getsearchWord = () => { if(window.location.search && window.location.search.includes('search=')){ return window.location.search.split('search=')[1] } //뒤에 있는 값을 반환 return ''; }; this.state={ startIdx : 0, sortBy : getSortBy(), region: '', searchWord: getsearchWord(), cities:'', }; const header = new Header({ $app, initialState:{ sortBy:this.state.sortBy, searchWord:this.state.searchWord }, handleSortChange: async(sortBy) => { const pageUrl = `/${this.state.region}?sort=${sortBy}`; history.pushState( null, null, this.state.searchWord ? pageUrl + `&search=${this.state.searchWord}` : pageUrl ); //변경된 정렬기준을 적용한 새로운 데이터를 불러옴 (매개변수로 전달받은 새로운 정렬기준인 sortBy 값을 넣어야함) const cities = await request(0, this.state.region, sortBy, this.state.searchWord); // 변경된 상태값을 업데이트 this.setState({ ...this.state, startIdx:0, sortBy: sortBy, cities: cities, }); }, handleSearch: async(searchWord) => { //웹사이트 주소를 알맞게 변경 history.pushState( null, null, `/${this.state.region}?sort=${this.state.sortBy}&search=${searchWord}` ); const cities = await request(0, this.state.region, this.state.sortBy, searchWord); this.setState({ ...this.state, startIdx:0, searchWord: searchWord, cities: cities }) }, }); const regionList = new RegionList({ $app, initialState:this.state.region, handleRegion: async(region) => { history.pushState(null, null, `/${region}?sort=total`); const cities = await request(0, region, 'total'); console.log("cities",cities) this.setState({ ...this.state, startIdx: 0, region: region, sortBy: 'total', cities: cities, searchWord: '', }); }, }); const cityList = new CityList({ $app, initialState:this.state.cities, // 아래는 더보기 버튼을 눌렀을 때 실행되는 것 handleLoadMore: async() => { const newStartIdx = this.state.startIdx + 40; const newCities = await request(newStartIdx, this.state.region, this.state.sortBy, this.state.searchWord); this.setState({ ...this.state, startIdx : newStartIdx, cities:{ cities:[...this.state.cities.cities, ...newCities.cities], isEnd: newCities.isEnd, } }) } }); const cityDetail = new CityDetail(); this.setState = (newState) => { this.state = newState; cityList.setState(this.state.cities); header.setState({sortBy:this.state.sortBy, searchWord:this.state.searchWord}); regionList.setState(this.state.region); }; const init = async() => { const cities = await request(this.state.startIdx, this.state.sortBy, this.state.region, this.state.searchWord); this.setState({ ...this.state, cities: cities, //api 호출의 결과인 cities }); }; init(); } export default function RegionList({$app, initialState, handleRegion}){ this.state = initialState; this.$target = document.createElement('div'); this.$target.className = 'region-list'; this.handleRegion = handleRegion; $app.appendChild(this.$target); this.template = () => { const regionList = [ '🚀 All', '🌏 Asia', '🕌 Middle-East', '🇪🇺 Europe', '💃 Latin-America', '🐘 Africa', '🏈 North-America', '🏄 Oceania', ]; let temp = ``; regionList.forEach((elm) => { let regionId = elm.split(' ')[1]; temp += `<div id=${regionId}>${elm}</div>`; }); return temp; }; this.render = () => { this.$target.innerHTML = this.template(); let $currentRegion; if(this.state){ $currentRegion = document.getElementById(this.state); $currentRegion && ($currentRegion.className = 'clicked'); } else { document.getElementById('All').className = 'clicked'; } const $regionList = this.$target.querySelectorAll('div'); $regionList.forEach((elm) => { elm.addEventListener('click', () => { this.handleRegion(elm.id); }); }); }; this.setState = (newState) => { this.state = newState; this.render(); }; this.render(); }

  • javascript
  • rest-api
  • spa
  • dom
최유진 댓글 1 좋아요 0 조회수 262

스낵바를 만들 때 snackBarContext와 snackBarSetContext

해결됨

코어 프런트엔드 UI - Part 2

스낵바를 만들 때 snackBarContext와 snackBarSetContext를 둘로 나누셔서 관리하는데 이렇게 하신 이유나 장점을 정확히 알 수 있을까요? 단점도 알려주시면 감사드리겠습니다.

  • react
  • typescript
  • dom
  • ui
  • vanilla-js
oridori2705 댓글 2 좋아요 0 조회수 197

select값이 출력이 안돼요

해결됨

한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지

input 값은 나오는데 select 값은 출력이 안돼요 ㅠ 오류 메세지도 따로 나오는 건 없고 console.log로 cities 값을 볼려고 했는데 빈 Array가 나옵니다 ㅠ import Header from "./components/Header.js"; import RegionList from "./components/RegionList.js"; import CityDetail from "./components/CityDetail.js"; import CityList from "./components/CityList.js"; import { request } from "./components/api.js"; export default function App($app){ const getSortBy = () => { if (window.location.search){ return window.location.search.split('sort=')[1].split('&')[0]; } return 'total'; }; const getSearchWorld = () => { if(window.location.search && window.location.search.includes('search=')){ return window.location.search.split('search=')[1] } //뒤에 있는 값을 반환 return ''; }; this.state={ startIdx : 0, sortBy : getSortBy(), searchWorld: getSearchWorld(), region: '', cities:'', }; const header = new Header({ $app, initialState:{ sortBy:this.state.sortBy, searchWorld:this.state.searchWorld }, handleSortChange: async(sortBy) => { const pageUrl = `/${this.state.region}?sort=${sortBy}`; history.pushState( null, null, this.state.searchWorld ? pageUrl + `&search=${this.state.searchWorld}` : pageUrl ); //변경된 정렬기준을 적용한 새로운 데이터를 불러옴 (매개변수로 전달받은 새로운 정렬기준인 sortBy 값을 넣어야함) const cities = await request(0, this.state.region, sortBy, this.state.searchWorld); console.log(cities) // 변경된 상태값을 업데이트 this.setState({ ...this.state, startIdx:0, sortBy: sortBy, cities: cities, }); }, handleSearch: async(searchWorld) => { //웹사이트 주소를 알맞게 변경 history.pushState( null, null, `/${this.state.region}?sort=${this.state.sortBy}&search=${searchWorld}` ); const cities = await request(0, this.state.region, this.state.sortBy, searchWorld); this.setState({ ...this.state, startIdx:0, searchWorld: searchWorld, cities: cities }) }, }); const regionList = new RegionList(); const cityList = new CityList({ $app, initialState:this.state.cities, // 아래는 더보기 버튼을 눌렀을 때 실행되는 것 handleLoadMore: async() => { const newStartIdx = this.state.startIdx + 40; const newCities = await request(newStartIdx, this.state.sortBy, this.state.region, this.state.searchWorld); this.setState({ ...this.state, startIdx : newStartIdx, cities:{ cities:[...this.state.cities.cities, ...newCities.cities], isEnd: newCities.isEnd, } }) } }); const cityDetail = new CityDetail(); this.setState = (newState) => { this.state = newState; cityList.setState(this.state.cities); header.setState({sortBy:this.state.sortBy, searchWorld:this.state.searchWorld}); }; const init = async() => { const cities = await request(this.state.startIdx, this.state.sortBy, this.state.region, this.state.searchWorld); this.setState({ ...this.state, cities: cities, //api 호출의 결과인 cities }); }; init(); }

  • javascript
  • rest-api
  • spa
  • dom
최유진 댓글 2 좋아요 1 조회수 256

왜 전부다 div태그로 만드는지 궁금합니다.

해결됨

웹 프론트엔드를 위한 자바스크립트 첫걸음

강사님 강의를 들으면서 의문이 들었는데 강사님 버튼 부분으로 되어있는 것들을 div태그로 전부다 만드시던데 혹시 이유가 따로 있을까요??? 북마크를 추가하는 부분이나 취소, 추가 부분은 button태그를 사용하거나 북마크를 입력하는 div태그 전체를 form태그로 묶어서 사용하는게 좀 더 좋지 않을까요?? 강사님이 div 태그만 사용하시던데 혹시 이유가 따로 있으신건가요??

  • javascript
  • dom
  • div
김용인 댓글 2 좋아요 1 조회수 300

인기 태그

인프런 TOP Writers

주간 인기글