본문 바로가기
반응형

Programming/React48

Gatsby Tailwind CSS 적용하기 1. Tailwind CSS 와 PostCSSnpm install tailwindcss postcss autoprefixer gatsby-plugin-postcss 2. Tailwind CSS 초기화npx tailwindcss inittailwind.config.js 파일이 생성됨3. PostCSS 설정프로젝트 루트 디렉토리에 postcss.config.js 파일을 생성한다.module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, },} 4. Gatsby 설정파일에 PostCSS 플러그인 추가gatsby-config.jsmodule.exports = { ... plugins: [ `gatsby-plugin-postcss`,.. 2024. 7. 30.
Next.js 14 버전 Netlify에 배포하기 1. next.config.mjs 수정 - 위와 같은 package.json 이 있다고 할 때, "npm run build" 를 하면 .next 폴더가 만들어지는데, next.config.mjs파일을 아래와 같이 수정해서 out파일을 배포하도록 설정을 바꿔줘야함. - 이미지 등의 경로를 제대로 인식할 수 있도록 basePath를 설정합니다.  [Next.js 의 모든 URL 앞에 추가되는 기본 경로를 설정]/** @type {import('next').NextConfig} */const nextConfig = { output: 'export', basePath: '', images: { unoptimized: true, },};export default nextConfig; 예전에는 next.. 2024. 7. 27.
개츠비(Gatsby) Disqus 댓글기능 달기 이번엔 개츠비(Gatsby) 블로그에 Disqus 댓글 기능을 추가해보도록 하겠습니다. [ 목차 ] 1. Disqus.com에 댓글 추가할 사이트정보 입력 Disqus.com에 로그인 후 Site Admin 으로 이동하여 기본 정보들을 입력하여 내 사이트를 추가해줍니다. 그리고 설치방법을 찾아보면 Gatsby에 반영하는 방법이 나옵니다. [ Site Admin > 내 사이트 선택 > Installation > Gatsby 선택 ] Disqus에서는 아래와 같은 형식으로 안내를 합니다. 단 config에서 괄호가 두개 들어가야합니다. 안내와 조금 차이가 있습니다. import { Disqus } from 'gatsby-plugin-disqus'; const Template = () => ( /* Page .. 2023. 8. 4.
개츠비(Gatsby) 구글 서치콘솔 등록 (Google Search Console) [ 목차 ]구글 서치콘설에 등록하기 위해서는 3단계를 거쳐야 합니다. 1. sitemap.xml 2. robots.txt3. Google Search Console 등록 1. Sitemap.xml 생성가장 먼저 sitemap.xml을 생성합니다. 생성 방법은 플러그인 추가로 쉽게 진행할 수 있습니다. gatsby-plugin-sitemap, gatsby-plugin-advanced-sitemap 플러그인을 추가해줍니다.npm i gatsby-plugin-sitemap// gatsby가 버전 5로 올라가면서 아래의 플러그인은 아직 설치가 안되고 있습니다.npm i gatsby-plugin-advanced-sitemapgatsby-config.js 에 플러그인을 추가해줍니다.module.exports = {.. 2023. 8. 4.
개츠비(Gatsby) 마크다운 파일과 이미지 처리하기 사실...여러 예제와 뤼튼 AI를 이용해서 하루 종일 고생하며 방법을 찾아봤는데, 지금도 왜 되었는지 잘 모르겠습니다. 예제를 따라 해도 안되던게 갑자기 됩니다. 우선 코드만 남겨놓습니다. 1. 마크다운 파일 읽어오는 옵션 'gatsby-source-filesystem'은 기본적으로 설치되었을겁니다. 마크다운 파일들을 모아놓는 곳을 아래와 같이 설정해줍니다. // gatsby-config.js module.exports = { siteMetadata: { ... }, plugins: [ ..., { resolve: `gatsby-source-filesystem`, options: { name: `posts`, path: `${__dirname}/content/posts`, }, }, ... ], }; 2.. 2023. 7. 30.
개츠비(Gatsby) 마크다운 블로그 만들기 시작하기 정적사이트 생성기(SSG, Static Site Generator)에 대해 공부하다보니 다시 Gatsby에 대한 흥미가 돌기 시작해서 오랫만에 Gatsby로 프로젝트를 만들어봤습니다. 예전에 이걸 공부했던 적이 있었나 싶을 정도로 하나도 기억이 안나더군요. React에 대한 두려움으로 React 계통의 프레임워크들은 무조건 멀리했었던 것 같기도 하고, 사실은 Gatsby, GraphQL에 대해 정확히 공부한적이 없었던 것 같기도 하네요. 그래서 오늘은 설치하고 마크다운 문서 표기하기까지 알게된 내용을 정리해볼까 합니다. [ 목차 ] 1. Gatsby란? Gatsby는 서두에 말했듯이 React에 기반한 정적사이트 생성기(SSG, Static Site Generator)입니다. 예전부터 Ruby on Ra.. 2023. 7. 26.
React toolkit을 이용한 React counter 1. 라이브러리 설치 yarn add redux react-redux @reduxjs/tookit 2. index.js Reducer 연결 및 store 생성 import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App"; import reportWebVitals from "./reportWebVitals"; import { configureStore } from "@reduxjs/toolkit"; import rootReducer from "./reducers"; import { Provider } from "react-redux"; const store = configure.. 2021. 8. 23.
React에서 Kakao 지도 api 사용하기 - 지도에 표시하기 1. 지도에서 좌표-주소 변환 geocoder 라는 것을 사용해야하는데, services라이브러리를 써야합니다. 라이브러리는 api 요청할 때 url에 추가해서 보내면 됩니다. (kakao 예제에서 제공하는 cluster, drawing도 함께 추가해 넣었습니다.) 2. 우선 화면에 무언가 표시를 해봅시다. 예제는 kakao에서 제공되는 kakao 제주 사옥을 찾는 것 같습니다. import React, { useEffect } from 'react'; const { kakao } = window; const MapContainer = () => { useEffect(() => { const container = document.getElementById('myMap'); const options = {.. 2021. 8. 11.
React에서 Kakao 지도 api 사용하기 1. App key 발급 https://apis.map.kakao.com/web/guide/ 사이트에 접속해서 순서대로 진행합니다. 우선 카카오 개발자사이트 (https://developers.kakao.com) 접속하여 회원가입을 하고, 애플리케이션 추가하기를 통해 앱 생성을 합니다. 생성된 앱(mymap)을 클릭해 들어가면 사용할 수 있는 앱 키가 제공됩니다. 이렇게 간단히 앱키 발급이 완료되었습니다. 2. Sample React App 생성 리액트 앱을 생성하고, 간단히 소스를 추가해보겠습니다. 1) public/index.html 아래 코드를 /public/index.html 파일의 내부에 붙여넣습니다. 2) 지도를 띄우는 코드 작성 import React, { useEffect } from 'r.. 2021. 8. 10.
Gatsby 시작하기 (with Typescript) 0. Gatsby-cli 설치 npm install -g gatsby-cli 1. Gatsby 프로젝트 생성 gatsby new [프로젝트명] or npx gatsby-cli new [프로젝트명]// gatsby-cli설치 없이 수행할 때 yarn remove gatsby-plugin-manifest gatsby-plugin-gatsby-cloud // 필요없는 라이브러리 삭제 2. 타입스크립트 설치 yarn add typescript --dev yarn add gatsby-plugin-typescript 3. gatsby-config.js 파일 수정 module.exports = { siteMetadata: { title: `Gatsby Default Starter`, description: `Kick.. 2021. 7. 4.
Recoil을 활용한 비동기 요청 예제 1. Library 설치 yarn add recoil 2. 구성 /src ㄴ components * UserList.jsx ㄴ recoil * state.js *App.js *Index.js 3. 코드 (1) src/App.js import React, { ErrorBoundary } from "react"; import { RecoilRoot } from "recoil"; import UserList from "./components/UserList"; function App() { return ( ); } export default App; (2) src/recoil/state.js import { atom, selector } from "recoil"; export const userListStat.. 2021. 6. 30.
SWR을 활용한 비동기 요청 예제 1. Library 설치 yarn add swr 2. 폴더 구성 Counter는 참고로 작성했는데, 본 포스트에서 구성하지는 않겠습니다. 비동기로 서버에서 User목록만 불러와서 보여주는 부분만 코드로 남김니다. /src ㄴcomponents *Users.jsx ㄴcustomHooks *useUsers.js *App.js *index.js 3. 코드 (1) App.js import Users from "./components/Users"; import Counter from "./components/Counter"; function App() { return ( ); } export default App; (2) src/customHooks/useUsers.js import useSWR from "swr.. 2021. 6. 29.
React-query 를 활용한 비동기 요청 예제 1. Library 설치 yarn add react-query 2. 프로젝트 구조 /src ㄴcomponents * RQ1 (테스트용) * RQ2 (실 사용 컴포넌트) ㄴcustomHooks * useUsers.js *App.js *index.js 3. 코드 (1) App.js import { QueryClient, QueryClientProvider } from "react-query"; import RQ2 from "./components/RQ2"; const queryClient = new QueryClient(); function App() { return ( ); } export default App; (2) src/customHooks/useUsers.js import { useQuery } .. 2021. 6. 29.
Redux-Saga 를 활용한 비동기 요청 예제 1. 프로젝트 생성 yarn create react-app . 2. 라이브러리 설치 yarn add redux react-redux redux-actions axios redux-saga redux-devtools-extension 3. 프로젝트 구성 프로젝트 구성은 아래와 같이 할 계획입니다. /src 하위부분만 살펴보면 되겠습니다. /src ㄴ components * Leader.jsx ㄴ containers * LeaderContainer.jsx ㄴ lib * api.js (서버에 요청하는 비동기 함수 정의부분) ㄴ modules * index.js (redux와 saga를 통합하는 부분) * leader.js ( action 타입, action 생성함수, redux, saga 정의하는 부분) * .. 2021. 6. 29.
SWR로 로컬 상태 컨트롤 - Counter import useSWR from "swr"; function useCounter() { const { data, mutate } = useSWR("state", () => window.count); return { data: window.count || 0, mutate: (count) => { window.count = count; return mutate(); }, }; } export default function Counter() { const { data, mutate } = useCounter(); const handleInc = () => mutate(data + 1); const handleDec = () => mutate(data - 1); return ( count: {data} in.. 2021. 6. 26.
Next.js 시작하기4 - 설정파일 1. next.config.js module.exports = { reactStrictMode: true, trailingSlash: false, // 뒤쪽 슬래시를 붙일 것인지.. env: { SANITY_PROJECT_ID: 'ozi5ivc6', //Sanity ID를 환경변수로 지정 } } 2021. 6. 20.
Next.js 시작하기3 - 스타일링 1. 라이브러리 설치 yarn add @sanity/block-content-to-react yarn add react-syntax-highlighter 2. BlogPostDetail.jsx import {Col, Row } from 'antd' import BlockContent from '@sanity/block-content-to-react' import SyntaxHighlighter from 'react-syntax-highlighter' const serializers = { types: { code: ({node}) => { const { code } = node; return ( {code} ) }, video: ({ node }) => { return video }, link: ({ n.. 2021. 6. 20.
Next.js 시작하기2 - 스타일링 1. 라이브러리 설치 yarn add antd @ant-design/icons// ant design yarn add dayjs// 날짜 변환 라이브러리 2. pages/_app.js 파일에 반영 -> 전체 적용 import 'antd/dist/antd.css' // p.slug === home.mainPostUrl); const otherPosts = posts.filter(p => p.slug !== home.mainPostUrl); console.log(mainPost); console.log(otherPosts); return ( ) } export async function getStaticProps() { const sanityService = new SanityService(); const .. 2021. 6. 20.
Next.js 시작하기 (Sanity Blog 작성 완료된 경우) 1. 프로젝트 생성 및 Library 설치 yarn create next-app . yarn add @sanity/client//Sanity 연결하여 Data를 가져오기 위한 라이브러리 2. 시작 yarn dev yarn start는 빌드 이후 가능합니다. 3. 라우팅 설정 (기초) 폴더/페이지구조url pages/index.js -> / pages/blog/index.js-> /blog pages/blog/first-post.js->/blog/first-post pages/dashboard/setting/username.js->/dashboard/settings/username pages/blog/[slug].js->/blog/:slug(/blog/hello-world) pages/[username]/.. 2021. 6. 20.
Recoil 따라하기 - TodoList 무작정 따라한 소스를 기록으로 남김니다. 1. App.js RecoilRoot 를 사용하여 TodoList 요소를 감싸준다. import React from 'react'; import TodoList from './components/TodoList' import { RecoilRoot } from 'recoil'; function App() { return ( ); } export default App; 2. ./src/recoil/state.js 작성 import { atom } from 'recoil'; export const todoListState = atom({ key: 'todoListState', default: [], }); 3. ./src/components/TodoList.jsx 작.. 2021. 5. 28.
Nodejs V14 ESM 문법 적용하기 - 리액트를 다루는 기술 backend 주의점 "리액트를 다루는 기술" 의 22장...mongodb 연동하기 과정에서 Koa 백엔드에 ESM을 적용하는 부분이 있는데, 현재 Node 14 버전에서 주의해야할 점과 함께 몇가지 정리해보고하 합니다. 1. 라이브러리 설치 해당 과정에서는 ESM이 외에도 몇가지 라이브러리가 필요합니다. koa, koa-bodyparser, koa-router, mongoose, dotenv 등 말이죠. ESLint옵션 설정하는 부분은 제외하도록 하겠습니다. (VSCode에 설치한 ESLint 기능에, 추가 설정했을 경우 달라지는 부분을 잘 몰라서 이부분은 제외하고 사용했습니다.) 아래의 package.json을 보면 필요한 라이브러리들을 확인할 수 있을 것입니다. { "name": "05_react_backend", "v.. 2021. 4. 10.
Newsapi api 키 발급받기 1. https://newsapi.org/register에 가입합니다. News API – Search News and Blog Articles on the Web Get JSON search results for global news articles in real-time with our free News API. newsapi.org 가입 완료시 나오는 API Key를 저장해둡시다. 나중에 API 요청할 때 써먹어야 합니다. 2. 한국 Link에 들어가봅니다. https://newsapi.org/s/south-korea-news-api News API – Search News and Blog Articles on the Web Get JSON search results for global news a.. 2021. 3. 23.
Storybook 사용하기 비주얼 테스트 도구인 스토리북에 대해 알아보겠습니다. 1. 설치 npx -p @storybook/cli sb init .storybook폴더가 자동 생성되고, 그 안에 story파일을 로딩해주는 main.js 와 preview.js 파일이 있습니다. main.js에는 ...story.js파일을 자동 추가/로딩해주는 부분과 addon 설정부분이 있습니다. (preview.js는 아직 잘 모르겠습니다.ㅠㅠ) package.json에도 storybook 스크립트가 추가되었습니다. (모두 이전 버전에서 수동 생성해주던 부분임...) 2. Sample 컴포넌트 작성 기존 컴포넌트들이 있으면 활용해도 되지만, 저는 새로 만든 프로젝트에서 테스트할 용도로 간단한? 컴포넌트 하나를 만들겠습니다. import React.. 2021. 3. 18.
MongoDB 다운로드 설치 및 Compass 연결 MongoDB 설치파일 다운로드 위치를 몰라서 기록해놓습니다. 아울러 Compass에서 처음 접속하는 방법도 함께 공유합니다. 1. Download Site (www.mongodb.com/try/download/community)접속 2. 설치 (설치 중간에 함께 추천하는 Compass 도 설치합니다.) 3. 확인 정상 설치되었을 경우 커맨드 창에 mongo 라고 입력해보면 버전정보 등이 나타납니다. 4. Compass 실행 'mongodb://localhost:27017'을 입력하고 Connect를 누르면.. 현재의 데이터베이스들이 나타납니다. ~끝~ 2021. 3. 7.
React - Apache에 배포하기 1. Build "create-react-app ." 명령으로 react app 생성 후 배포를 위해서는 아래의 명령으로 buid 합니다. npm run build 이렇게 하면 build 폴더가 생성되는데 필요한 파일을 서버가 작동하는 폴더에 위치시키면 됩니다. 2. httpd.conf 항목 추가 매번 build된 파일을 apache가 서비스하는 폴더로 옮기는 작업은 번거롭습니다. 현재 작업중인 폴더를 직접 서비스하도록 추가하고 싶다면, httpd.conf파일에 아래의 항목을 추가해줍니다. Alias /react "D:/05_Program_dev/03_web/04_react_hello/build" Options Indexes FollowSymLinks AllowOverride None Require al.. 2021. 2. 27.
React강좌3 - Redux0. redux 구조 과제를 따라 수행하면서도 리덕스(Redux) 개념이 잘 안서는데, 나름 이해한 부분을 정리해봅니다. 리덕스는 store로부터 데이터를 직접 공급받기 위한 관리체계 개념입니다. 1개의 store에서 모든 데이터를 관리하죠. 동작 순서는 아래와 같으며, Action, Reducer를 별도 파일로 구성하고, Store도 App.js에서 생성해주어야 합니다. 1. Action '액션 생성자'에서 Action에 대한 정의만합니다. 단순히 어떤 동작(타입)인지만 정의합니다. 실제 'Action' 이라고 할 수 있는 '동작'의 개념은 Reducer가 수행합니다. 예로 아래와 같이 사용합니다. 이전 수행한 과제 블로그를 보시면 type 마져도 ActionType.js에 모아서 정의해 놓고 import해서 쓰기도 합니다.. 2020. 8. 9.
React강좌3 - Redux5. react-redux를 이용한 store연결 1. Provider: 서비스 제공 컴포넌트 예) 2.컴포넌트를 redux에 연결하는 또다른 함수를 반환함 connect({...options]) 예) connect()(Counter) store에 연결 된 새로운 컴포넌트 클래스가 반환됨. 옵션이 없으면 this.props.store로 접근 가능 옵션 connect( [mapStateToProps], //state 를 해당 컴포넌트의 props로 연결 [mapDispatchToProps], //dispatch한 함수를 props로 연결 [mergeProps], //state와 dispatch를 동시에 사용할 경우. 잘 사용되지 않음 [options] // pure=true: 불필요한 업데이트를 하지 않음, withRef=false: 잘 사용하지 않음 ).. 2020. 8. 9.
React강좌3 - Redux4. Store 예시 어플리케이션의 현재 상태를 지니고 있음 store역할 dispatch(action) : 새 상태를 현 상태에 갈아끼움 getState() : 현재 상태를 반환 subscribe(listener): 상태가 바뀔때마다 실행할 콜백함수(listener) 등록 replaceReducer(nextReducer) 추가로, redux-devtools-extension을 설치하고, 크롬에서 Redux DevTools를 설치한다. yarn add redux-devtools-extension --dev 1. src/index.js store예시 import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from '.. 2020. 8. 8.
React강좌3 - Redux3. Reducers 변화를 일으키는 함수 순수해야함 비동기 X 전달받은 인수변경 X 동일한 인수 = 동일한 결과 이전상태와 액션을 받아서 다음상태를 반환한다. (이전상태 변경이 아님) (previous State, Action) => newState SRC/Reducers 폴더안에 아래 3 파일을 만든다. 1. Counter.js (숫자 계산) 2. ui.js (색상 변경) 3. index.js (Reducer 통합) 1. Counter.js import * as types from '../Actions/ActionTypes'; //초기상태 정하기 const initialState = { number: 0, //최초 초기상태 정의 }; export default function counter(state = initialSt.. 2020. 8. 8.
React강좌3 - Redux2. Action작성 1. 값 증가 액션 2. 값 감소 액션 3. 색 변경 액션 SRC/Actions폴더에 아래 2개의 파일 생성 1. ActionTypes.js export const INCREMENT = "INCREMENT"; export const DECREMENT = "DECREMENT"; export const SET_COLOR = "SET_COLOR"; 2. index.js // 액션 생성자 //import { INCREMENT, DECREMENT, SET_COLOR } from './ActionTypes'; import * as types from './ActionTypes'; //위 구문과 동일한 의미 export function increment() { return { type: types.INCREMENT .. 2020. 8. 8.
반응형