[리액트]gatsby+typescript 로 dynamic router 만들기

HardCarry·2023년 10월 24일
post-thumbnail

- 목표

localhost/admin/{dynamicURL} 구현

관리자화면에서는 유저목록이 나오고,
유저목록을 클릭하면 유저상세 페이지가 나오게 하려고 한다.

예를들어

localhost/admin <- 유저 목록이 나옴.

localhost/admin/12345 <- userID 12345 의 상세 페이지가 나오고
localhost/admin/222 <- userID 222 의 상세 페이지가 나오게 한다.

- 구현

gatsby 에서 multi router 하기 위해서 아래 설치

npm i gatsby-plugin-dynamic-routes
npm install gatsby-plugin-typescript
npm i @reach/router


폴더 구조 아래와 같이 구성


프로젝트폴더
 └gatsby-node.ts
 └gatsby-config.ts
 └src
	└pages
		└admin
        	└admin.tsx
        └user
        	└[user].tsx
     Routes ( 확장자 없는 파일 입니다 )
 

각각의 파일 구성

gastsby-node.ts

const path = require("path");

exports.onCreatePage = async ({ page, actions }: { page: Page; actions: Actions }) => {

    const {createPage} = actions;

    // build 할 때 호출 한다.
    
    if(page.path.match(/^\/user/)){
        createPage({
            path: "/user/",
            matchPath: `/user/*`,
            component: path.resolve(`src/pages/user/[user].tsx`)
        })
    }
    else if(page.path.match(/^\/test/)){
        createPage({
            path: "/test/",
            matchPath: `/test/*`,
            component: path.resolve(`src/pages/test/[test].tsx`)
        })
    }
}

gastby-config.ts

plugins: [
    `gatsby-plugin-dynamic-routes`,
    ]

admin.tsx

import React from 'react'
 const admin: React.FC<PageProps> = () => {
  return (
      <>
        Admin페이지, 유저목록이 표시될 페이지
      </>
    );
}

user.tsx

 
import React from 'react'
 const User: React.FC<PageProps> = () => {
  return (
      <>
        User 상세 정보가 표시 될 페이지
      </>
    );
}

Routes

const path = require("path");
module.exports = [
	{
    	path: "/admin/",
    	component: path.resolve(`src/pages/admin/admin.tsx`),
  	},
];



- 확인 해보기

npm start

localhost/admin
localhost/user/1234

완료.

profile
안녕하세요, 하드캐리입니다

0개의 댓글