묻고 답해요
161만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결[React 2부] 고급 주제와 훅
[1.3.6 상태정의] state 관련
OrderPage/index.jsx 생성자(constructor)의 state 부문에서 this.state = {order: null,} 와 this.state = {}의 차이가 있나요?(this.state = {order: null,} 로 선언한 이유가 궁금합니다. )
-
미해결처음 만난 리액트(React)
9강 && 논리연산자 질문입니다.
소플님, 강의 정말 잘 듣고 있습니다. 감사합니다~ 소플님 질문 있습니다. 9-1강에서 && 논리 연산자 설명에서 count = 0 인 경우. return (count && <p>잘 듣고 있습니다~ {count} 번</p>); 상기 결과는 0으로 출력 된다고 설명 들었는데요. 9-1 강의에서isLoggedIn 값이 false로 넘겨졌을 때에 return (isLoggedIn && 환영합니다.<button>로그인</button>);인 경우의 결과는 false<button>로그인</button> 이렇게 false가 찍혀야 할것 같은데 소플님의 영상 화면에서는 버튼 밖에 안보입니다. 왜 그런 걸까요?
-
해결됨Next + React Query로 SNS 서비스 만들기
_lib 폴더는 어떤 용도인가요?
_lib 폴더는 어떤 용도로 구분되어져 있는 폴더일까요??
-
미해결처음 만난 리덕스(Redux)
첫강의에 팝업 뜬 내용 못읽고 꺼버렸는데 무슨 내용이었는지 아시는 분
첫강의에 팝업 뜬 내용 못읽고 꺼버렸는데 무슨 내용이었는지 아시는 분 있으신가요ㅠㅠ최초 1회만 뜨는 거라 그런지 재접속 해봐도 안뜨네요 ㅠ
-
해결됨만들면서 배우는 리액트: 컴포넌트 설계와 리팩토링
function vs const
App()은 function 키워드를 사용하고 handleClick()은 const를 사용하셨는데 컨벤션 같은게 있을까요?
-
미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
라우터에서 빈 화면 나오시는 분들
Switch 문이 버전 6에서 사라졌다고 하네요. Route에서 props로 element 보내는 방법을 사용해서 코드를 수정해보았습니다. 참고하시면 좋을 거 같아요. import { BrowserRouter as Router, Routes, Route } from "react-router-dom" import NavBar from "./components/views/NavBar/NavBar"; import Footer from "./components/views/Footer/Footer"; import LandingPage from "./components/views/LandingPage/LandingPage"; import LoginPage from "./components/views/LoginPage/LoginPage"; import RegisterPage from "./components/views/RegisterPage/RegisterPage"; function App() { return ( <> <NavBar /> <Router> <Routes> <Route path="/" element={<LandingPage />} /> <Route path="/login" element={<LoginPage />} /> <Route path="/register" element={<RegisterPage />} /> </Routes> </Router> <Footer /> </> ); } export default App;
-
해결됨손에 익는 Next.js - 공식 문서 훑어보기
import 절대경로 설정 방법 질문 드립니다!
조은님 안녕하세요 🙂 강의 잘 보았습니다!강의를 보다가 문득 궁금한 점이 있는데요! import 문 통해서 절대경로로 파일을 불러올 때, 전역에 있는 tsconfig.json 내에서 파일별로 일일이 수동 설정을 해주어야하는 걸로 아는데 조은님께서는 자동으로 @가 붙여진 형태로 불러와지는 거 같아서요! 혹시 따로 설정 어떻게 하셨는지 여쭤봐도 괜찮을까요?
-
해결됨Next + React Query로 SNS 서비스 만들기
No overload matches this call.
z-com\src\app\(beforeLogin)\_component\SignupModal.tsx파일에서 useFormState(OnSubmit, {message: null }); 해당 부분에서Type error:No overload matches this call.Overload 1 of 2, '(action: (state: { message: string; } | undefined) => { message: string; } | Promise<{ message: string; } | undefined> | undefined, initialState: { message: string; } | undefined, permalink?: string | undefined): [state: ...]', gave the following error.Argument of type '(prevState: any, formData: FormData) => Promise<{ message: string; } | undefined>' is not assignable to parameter of type '(state: { message: string; } | undefined) => { message: string; } | Promise<{ message: string; } | undefined> | undefined'.Target signature provides too few arguments. Expected 2 or more, but got 1.Overload 2 of 2, '(action: (state: { message: string; } | undefined, payload: FormData) => { message: string; } | Promise<{ message: string; } | undefined> | undefined, initialState: { message: string; } | undefined, permalink?: string | undefined): [state: ...]', gave the following error.Type 'null' is not assignable to type 'string'.ts(2769)에러가 발생합니다.제로초님 github 파일 3-2에 있는 부분을 복붙해서 하고 있는데 에러가 발생했습니다. 타이핑 에러는 아닌 것 같습니다.찾아보니 함수에 들어오는 매개변수의 타입이 예상한 타입과 일치하지 않을 때 발생한다고 하여서 message의 type을 any로 바꿔보아도 에러가 납니다 ..React 버전은 18버전이고 nextjs 는 14.0.4 버전입니다.어떤 부분을 수정해야 할지 모르겠습니다...
-
미해결[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
중고마켓 찜하기 토글 기능 데이터 값 저장법
안녕하세요.현재 찜하기 기능을 추가하는 작업을 진행중입니다.전체적으로 설명드리면 찜하기 Hook을 만들고 ProductDetail 컴포넌트에 Hook의 리턴 값을 보내어 작업하였습니다. 찜하기 API의 결과 값으로 off시 0, on 시 1을 출력하여 그 값을 state에 저장하여 상품디테일 컴포넌트로 리턴하여 작업하는 중입니다. 그런데 state의 초기값을 토글의 결과값을 가져와서 넣어주어야 하는데 어떻게 해야할지 잘 모르겠습니다. 제가 생각해본 방법으론 상품 컴포넌트에서 state를 새로 만들어 가져온 pick의 변수를 set에 담았더니 랜더링이 많아진다면서 오류가 떴습니다.혹시 제가 작업하는 방향이 틀린 것인지 궁금하고, 어떻게 문제를 해결해야할지 잘 몰라 질문 드립니다!
-
미해결Next + React Query로 SNS 서비스 만들기
Link와 클라이언트사이드 렌더링
안녕하세요 제로초님.이제 막 Next 강의 시작해서 기초부터 보고 있는데 이해가 되지 않는 부분이 있어 질문드립니다.next/link에 관한 부분인데요.공식문서보니까 next/link 사용시에 클라이언트 사이드 라우팅이 된다고 하는데그 말인 즉슨 link에 해당하는 페이지 컴포넌트의 자바스크립트를 미리 받아놓고 사용자가 Link로 이동할 때 클라이언트에서 페이지를 생성한다는 뜻으로 이해했는데요. 그럼 이동하는 페이지 컴포넌트에 console.log("하이")가 있으면 클라이언트, 즉 브라우저에 console.log가 출력되어야하는 거 아닌가요? 하지만 제 예상과 다르게 Link로 이동한 페이지 컴포넌트의 console.log는 서버에 출력되네요. 1. "use client"를 명시하지 않은 컴포넌트는 모두 서버에서 렌더링 되는 컴포넌트다2. Link로 이동하면 클라이언트 사이드 렌더링을 한다. 이 두 가지 개념이 어떻게 공존할 수 있는지, 위에 설명드린 케이스와 함께 잘 이해가 되지 않네요ㅜ
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
portfolio review 코드 말고 수업 예제 코드는 없을까요?
컴퓨터를 교체해서 앞에 수업했던 파일들이 다 날아갔는데 강의 뒷부분에서 재활용 되는 경우가 있더라구요.. 깃허브에는 포폴용 과제만 샘플 코드가 제공되는 것 같아서 혹시 수업 파일도 올려주실 수 있으실까요?
-
미해결코드로 배우는 React 19 with 스프링부트 API서버
react 프로젝트 설정 문제
프로젝트를 설정하고 되다가 다시 키니까 안되서 문의드립니다.제가 java 버전이 3개 정도 설치되어 있는 데 작업할 때 17로 수정해서 쓰고 다른 것 해야 할 때 11로 바꿔서 썼다가 오늘 17로 바꿔서 쓰는 데 자바버전이 안 먹히는 것 같아서 문의 드립니다.The supplied phased action failed with an exception.A problem occurred configuring root project 'mallapi'.Could not resolve all files for configuration ':classpath'.Could not resolve org.springframework.boot:spring-boot-gradle-plugin:3.1.10-SNAPSHOT.Required by: project : > org.springframework.boot:org.springframework.boot.gradle.plugin:3.1.10-SNAPSHOT:20240229.214127-20No matching variant of org.springframework.boot:spring-boot-gradle-plugin:3.1.10-SNAPSHOT:20240229.214127-20 was found. The consumer was configured to find a library for use during runtime, compatible with Java 11, packaged as a jar, and its dependencies declared externally, as well as attribute 'org.gradle.plugin.api-version' with value '8.5' but: - Variant 'apiElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.1.10-SNAPSHOT declares a library, packaged as a jar, and its dependencies declared externally: - Incompatible because this component declares a component for use during compile-time, compatible with Java 17 and the consumer needed a component for use during runtime, compatible with Java 11 - Other compatible attribute: - Doesn't say anything about org.gradle.plugin.api-version (required '8.5') - Variant 'javadocElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.1.10-SNAPSHOT declares a component for use during runtime, and its dependencies declared externally: - Incompatible because this component declares documentation and the consumer needed a library - Other compatible attributes: - Doesn't say anything about its target Java version (required compatibility with Java 11) - Doesn't say anything about its elements (required them packaged as a jar) - Doesn't say anything about org.gradle.plugin.api-version (required '8.5') - Variant 'mavenOptionalApiElements' capability org.springframework.boot:spring-boot-gradle-plugin-maven-optional:3.1.10-SNAPSHOT declares a library, packaged as a jar, and its dependencies declared externally: - Incompatible because this component declares a component for use during compile-time, compatible with Java 17 and the consumer needed a component for use during runtime, compatible with Java 11 - Other compatible attribute: - Doesn't say anything about org.gradle.plugin.api-version (required '8.5') - Variant 'mavenOptionalRuntimeElements' capability org.springframework.boot:spring-boot-gradle-plugin-maven-optional:3.1.10-SNAPSHOT declares a library for use during runtime, packaged as a jar, and its dependencies declared externally: - Incompatible because this component declares a component, compatible with Java 17 and the consumer needed a component, compatible with Java 11 - Other compatible attribute: - Doesn't say anything about org.gradle.plugin.api-version (required '8.5') - Variant 'runtimeElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.1.10-SNAPSHOT declares a library for use during runtime, packaged as a jar, and its dependencies declared externally: - Incompatible because this component declares a component, compatible with Java 17 and the consumer needed a component, compatible with Java 11 - Other compatible attribute: - Doesn't say anything about org.gradle.plugin.api-version (required '8.5') - Variant 'sourcesElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.1.10-SNAPSHOT declares a component for use during runtime, and its dependencies declared externally: - Incompatible because this component declares documentation and the consumer needed a library - Other compatible attributes: - Doesn't say anything about its target Java version (required compatibility with Java 11) - Doesn't say anything about its elements (required them packaged as a jar) - Doesn't say anything about org.gradle.plugin.api-version (required '8.5')
-
해결됨프론트엔드 개발자를 위한, 실전 웹 성능 최적화(feat. React) - Part. 1
이미지 CDN 만드는 방법
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 이미지 CDN 구축하는 구체적인 방법이 알고 싶은데 따로 강의 없나요?
-
해결됨손에 익는 Next.js - 공식 문서 훑어보기
VSCode 확장프로그램은 어떤 것을 사용하셨나요?
안녕하세요 강의 잘 들었습니다. 혹시 VSCode에 어떤 확장프로그램들을 사용하셨는지궁금합니다.강의 듣다보면, 자동완성 되는 부분들이 있는데,제 환경에서는 그런 VSCode UI가 안뜨더라구요. 감사합니다.
-
해결됨Next + React Query로 SNS 서비스 만들기
[28강 오류 해결] https://loremflickr.com 외부 이미지 불러오기 오류
Invalid src prop (https://loremflickr.com/640/480?lock=5661426936971264) on `next/image`, hostname "loremflickr.com" is not configured under images in your `next.config.js` faker를 통해 https://loremflickr.com 에서 외부 이미지를 가져올 때 위 오류 발생하시는 분들은 next.config.js 또는 next.config.mjs에 아래와 같이 추가해주시면 됩니다. /** @type {import('next').NextConfig} */ const nextConfig = { images: { remotePatterns: [ { protocol: "https", hostname: "loremflickr.com", port: "", pathname: "/640/480/**", }, ], }, }; export default nextConfig;
-
해결됨실무에 바로 적용하는 프런트엔드 테스트 - 1부. 테스트 기초: 단위・통합 테스트
navigate 관련 테스트에서 질문있습니다!
버튼을 눌렀을 때, navigate 하는 경우를 테스트할 때는 클릭 시 함수가 호출되었는지에 대한 테스트만 하면 되는 건가요??혹시, 특정 경로로 잘 이동되었는지에 대한 테스트를 하는 방법이 있는지 여부와 해당 테스트가 존재한다면 통합테스트인건지 단위 테스트인건지 궁금합니다! 그리고, 그런 테스트가 존재한다면 어떻게 assert할 수 있는지도 알고 싶습니다!
-
해결됨손에 익는 Next.js - 마이그레이션하기
기존 react 에서 navigate 에 state 로 데이터를 전달했습니다.
안녕하세요. 현재 react 로 구성되어 있는 프로젝트를 next.js 로 마이그레이션 하기 위해 강의 신청해서 들었습니다.마이그레이션 도중 질문이 있어서 글 남겨봅니다.1) 기존 react 에서 navigate 의 state 값으로 전달하던 데이터 들이 있습니다. 전달된 데이터는 location state 로 가져와서 사용했구요.2) next 12 버전 까지는 query 에 객체를 담아서 보낼수 있고 url 도 as 를 이용해서 제어할 수 있는걸 확인했습니다.3) 하지만 13버전 이후부터 next/router -> next/navigate 로 변경되면서 query 객체, as 가 삭제되어진 걸로 확인되는데 페이지 이동시 데이터를 전달하러면 url 에 그냥 꼬라박는 방법 뿐인지 질문 드립니다.
-
미해결Next + React Query로 SNS 서비스 만들기
안녕하세요 복습중인데 msw 404 (Not Found) 질문드립니다.
// http.ts import { createMiddleware } from "@mswjs/http-middleware"; import cors from "cors"; import express from "express"; import { handlers } from "./handlers"; const app = express(); const port = 9090; app.use( cors({ origin: "http://localhost:3000", optionsSuccessStatus: 200, credentials: true, }) ); app.use(express.json()); app.use(createMiddleware(...handlers)); app.listen(port, () => console.log(`Mock server is ruuning on port: ${port}`)); // handlers.ts import { http, HttpResponse } from "msw"; const CalendarData = [ { id: 0, date: "2024-03-01", memo: [ { id: 0, text: "식사", }, { id: 1, text: "운동", }, ], }, { id: 1, date: "2024-03-02", memo: [ { id: 0, text: "연차", }, { id: 1, text: "회의", }, ], }, { id: 2, date: "2024-03-03", reservation: 0, canceled: 0, noShow: 0, memo: [], }, { id: 3, date: "2024-03-04", memo: [ { id: 0, text: "공부", }, { id: 1, text: "휴식", }, ], }, { id: 4, date: "2024-03-05", memo: [], }, { id: 30, date: "2024-03-31", memo: [ { id: 0, text: "파티", }, { id: 1, text: "운동", }, ], }, ]; export const handlers = [ http.get("http://localhost:3000/api/calendar", ({}) => { return HttpResponse.json(CalendarData); }), ]; // browser.ts import { setupWorker } from "msw/browser"; import { handlers } from "./handlers"; const worker = setupWorker(...handlers); export default worker; // MSWComponent.tsx "use client"; import { useEffect } from "react"; export const MSWComponent = () => { useEffect(() => { if (typeof window !== "undefined") { if (process.env.NEXT_PUBLIC_API_MOCKING === "enabled") { require("@/mocks/browser"); } } }, []); return null; }; // msw api 요청 함수 export async function getCalendarData() { const res = await fetch(`http://localhost:3000/api/calendar`, { next: { tags: ["calendar"], }, cache: "no-store", }); if (!res.ok) { throw new Error("Failed to fetch calendar data"); } return res.json(); } // layout.tsx import type { Metadata } from "next"; import { Inter } from "next/font/google"; import "./globals.css"; import PortalWrap from "@/components/PortalWrap/PortalWrap"; import Toast from "@/components/Toast/Toast"; import { MSWComponent } from "@/mocks/MSWComponent"; import SSRQueryClientProvider from "@/libs/ReactQuery/SSRQueryClientProvider"; const inter = Inter({ subsets: ["latin"] }); export const metadata: Metadata = { title: "Create Next App", description: "Generated by create next app", }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <body className={inter.className}> <MSWComponent /> <SSRQueryClientProvider> {children} <PortalWrap /> <Toast /> </SSRQueryClientProvider> </body> </html> ); } // .env NEXT_PUBLIC_API_MOCKING=enabled NEXT_PUBLIC_MODE=local// package.json { "name": "planner", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint", "mock": "npx tsx watch ./src/mocks/http.ts" }, "dependencies": { "@tanstack/react-query": "^5.14.6", "classnames": "^2.5.1", "date-fns": "^3.3.1", "next": "^14.0.3", "react": "^18", "react-dom": "^18", "react-icons": "^5.0.1", "react-transition-group": "^4.4.5", "sass": "^1.71.1", "zustand": "^4.5.2" }, "devDependencies": { "@mswjs/http-middleware": "^0.9.2", "@tanstack/react-query-devtools": "^5.25.0", "@types/cors": "^2.8.17", "@types/express": "^4.17.21", "@types/node": "^20.10.5", "@types/react": "^18", "@types/react-dom": "^18", "@types/react-transition-group": "^4.4.10", "autoprefixer": "^10.0.1", "cors": "^2.8.5", "eslint": "^8", "eslint-config-next": "14.1.2", "express": "^4.18.2", "msw": "^2.0.11", "postcss": "^8", "tailwindcss": "^3.3.0", "typescript": "^5" }, "msw": { "workerDirectory": "public" } } npm run mock 를 사용해서 터미널에 Mock server is ruuning on port: 9090 이 나오는것까지 확인되었는데 GET http://localhost:3000/api/calendar 404 (Not Found) 콘솔에 이렇게 오류가 나옵니다.몇시간 동안 이것저것 수정해보고 했는데 어디서 잘못된건지 왜 요청을 못받아오는지 모르겠습니다ㅠ
-
해결됨[React 2부] 고급 주제와 훅
[2.4장 다이얼로그 1] 2.4.5 withLayout(풀이) 에 관한 질문입니다.
안녕하세요 선생님 혼자 해보는 과정중에 질문이 있습니다.import React from "react"; import Backdrop from "../components/Backdrop"; import Dialog from "../components/Dialog"; export const layoutContext = React.createContext({}); layoutContext.displayName = "LayoutContext"; export class Layout extends React.Component { constructor(props) { super(props); this.state = { dialog: null, }; this.setDialog = this.setDialog.bind(this); } setDialog(dialog) { this.setState({ dialog }); } render() { const value = { dialog: this.state.dialog, setDialog: this.setDialog, }; return ( <layoutContext.Provider value={value}> {this.props.children} </layoutContext.Provider> ); } } export const DialogContainer = () => ( <layoutContext.Consumer> {({ dialog }) => dialog && <Backdrop>{dialog}</Backdrop>} </layoutContext.Consumer> ); export const withLayout = (WrappedComponent) => { const WithLayout = (props) => ( <layoutContext.Consumer> {({ dialog, setDialog }) => { const openDialog = () => { console.log("openDialog") setDialog(<Dialog>hihi</Dialog>); }; const closeDialog = () => { setDialog(null); }; const enhancedProps = { openDialog, closeDialog, }; return ( <WrappedComponent {...props} {...enhancedProps}></WrappedComponent> ); }} </layoutContext.Consumer> ); return WithLayout; }; withLayout을 만들어서 openDialog, closeDialog를 enhancedProps로 전달을 하였습니다.import * as MyLayout from "../lib/MyLayout"; const Page = ({ header, children, footer, openDialog }) => ( <div className="Page"> <header>{header}</header> <main>{children}</main> <footer>{footer}</footer> <MyLayout.DialogContainer /> <button onClick={openDialog}>dialog</button> </div> ); export default MyLayout.withLayout(Page); Page에서 MyLayout.DialogContainer이 기본값이 null인데 button을 추가하여 고차컴포넌트에서 주입받은 openDialog를 사용하여 Dialog를 렌더링하는데 성공하였습니다.닫기도 해보고싶어서import * as MyLayout from "../lib/MyLayout"; const Dialog = ({ closeDialog }) => ( <div className="Dialog"> <header>header</header> <main>main</main> <footer>footer</footer> <button onClick={closeDialog}>closeDialog</button> </div> ); export default MyLayout.withLayout(Dialog);Dialog component에 닫기 버튼을 추가하려고 MyLayout.withLayout으로 감싸니초기화 전에 참조하려 했다는데 이 에러 자체는 이해가 가지만 왜 지금 위 상황이 이 에러에 해당되는 상황인지 이해가 가지 않습니다...
-
해결됨손에 익는 Next.js - 공식 문서 훑어보기
환경변수 오류
환경변수 설정해서 입력하면 오류가 나타납니다