일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
- llm을 활용 단어장 앱 개발일지
- study book
- Got
- BFS
- Algorithm
- Dreamhack
- rao
- 영상처리
- MDP
- bloc
- ARM
- Image Processing
- Flutter
- Widget
- Stream
- Kaggle
- DART
- PCA
- Computer Architecture
- pytorch
- 백준
- 파이토치 트랜스포머를 활용한 자연어 처리와 컴퓨터비전 심층학습
- C++
- MATLAB
- system hacking
- BOF
- BAEKJOON
- ML
- FastAPI
- fastapi를 사용한 파이썬 웹 개발
- Today
- Total
Bull
[Next.js] base64 변환 사이트 만들기#series of 3GNG 본문
series of 3GNG
강의 보는 게 귀찮아서, GPT로 능동적인 공부하기: 어차피 강의는 머리에 잘 안 남아..
결과
https://chun-bae.github.io/Base64onNext.js/
Base64
chun-bae.github.io
언젠가 한 번 계속 만들어야지... 만들어야지... 하다가 조만간 공공데이터 활용 대회로 Nextjs 쓸 거 같아서 겸사겸사 만들었다.
간단한 홈페이지이기 때문에 소요시간은 3~4시간 걸린 것 같다.
Next를 처음 다뤄봐서 환경설정이나 SSR, CSR 개념에 대해 숙지가 잘 안 되어 있었다.
프로젝트 생성
npx create-next-app@latest .
Typescript : No
ESLink : Yes
Tailwind CSS : Yes
src/ directory : Yes
App Router : Yes
import alias : No
NextUI
NextUI를 사용해보고 싶어서 NextUI를 설치했다.
참고 문서
https://nextui.org/docs/guide/installation
Installation
Get started with NextUI in the official documentation, and learn more about all our features!
nextui.org
NextUI 기본 설치
npm install -g nextui-cli
nextui add [사용할 컴포넌트]
이 설치만으로 안된 거 같아서 이것저것 인터넷에 있는 블로그 글 다 설치한 거 같긴한데 그 중에 가장 핵심적으로 tailwind를 따로 설치해주니 제대로 NextUI가 작동됐다.
tailwind.css 설치
npm install -D tailwindcss
npx tailwindcss init
따라해도 안되면 다른 블로그에 있는 거 다 설치받고 해보자.
그래도 안되면 설정문제.
tailwind.config.js
// tailwind.config.js
const {nextui} = require("@nextui-org/react");
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
"./node_modules/@nextui-org/theme/dist/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
backgroundImage: {
"gradient-radial": "radial-gradient(var(--tw-gradient-stops))",
"gradient-conic":
"conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",
},
},
},
darkMode: "class",
plugins: [nextui()],
};
공식 문서에 적힌 거 그대로 추가하면 됌.
File
layout.jsx
import "./globals.css";
export const metadata = {
title: "Base64",
description: "Convert Base64",
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
page.jsx
"use client";
import React, { useState } from "react";
import { Textarea, Button } from "@nextui-org/react";
export default function Home() {
const [originalText, setOriginalText] = useState("");
const [base64Text, setBase64Text] = useState("");
const [error, setError] = useState("");
const handleEncodeChange = (e) => {
setOriginalText(e.target.value);
};
const handleDecodeChange = (e) => {
setBase64Text(e.target.value);
};
const encodeBase64 = () => {
try {
const encodedData = btoa(unescape(encodeURIComponent(originalText)));
setBase64Text(encodedData);
setError("");
} catch (e) {
setError("Encoding failed. Please check the input.");
setBase64Text("Encoding failed. Please check the input.");
}
};
const decodeBase64 = () => {
try {
const decodedData = decodeURIComponent(escape(atob(base64Text)));
setOriginalText(decodedData);
setError("");
} catch (e) {
setError("Decoding failed. Please check if your input is valid base64.");
setOriginalText("Decoding failed. Please check if your input is valid base64.");
}
};
return (
<div className="flex flex-col items-center justify-center h-screen px-4">
<div className="flex justify-center w-full max-w-4xl mb-4 gap-4">
{" "}
<div className="flex flex-col w-1/2 pr-2">
<Textarea
label="Original Text"
placeholder="Enter text to encode..."
onChange={handleEncodeChange}
value={originalText}
variant="bordered"
fullWidth
minRows={30}
maxRows={30}
color="secondary"
/>
<div className="flex justify-center mt-4">
<Button onClick={encodeBase64} color="secondary" auto fullWidth>
Encode
</Button>
</div>
</div>
<div className="flex flex-col w-1/2 pl-2">
{" "}
<Textarea
label="Base64 Text"
placeholder="Enter base64 to decode..."
onChange={handleDecodeChange}
value={base64Text}
variant="bordered"
fullWidth
minRows={30}
maxRows={30}
color="secondary"
/>
<div className="flex justify-center mt-4">
<Button onClick={decodeBase64} color="secondary" auto fullWidth>
Decode
</Button>
</div>
</div>
</div>
</div>
);
}
코드설명
"use client";
React Hook (useState)를 사용해야되기 때문에 SSR이 기본인 Next에서 해당 파일은 CSR로 작동하도록 바꿔준다.
Hook을 안쓰고 SSR에서 async로 변수 바꾸는 방법도 있던데 나중에 배워보려고 한다!
const [originalText, setOriginalText] = useState("");
const [base64Text, setBase64Text] = useState("");
const [error, setError] = useState("");
originalText는 base64를 디코딩한 텍스트 or 원문
base64Text는 원문을 인코딩한 텍스트 or 디코딩할 base64문
error는 변환할 때 예외처리 메시지 저장용. 근데 없어도 상관없다. 어차피 각각의 Text변수로 알리기 때문.
const handleEncodeChange = (e) => {
setOriginalText(e.target.value);
};
const handleDecodeChange = (e) => {
setBase64Text(e.target.value);
};
<TextArea>에서 이벤트 발생 시 변수에 지속적으로 값을 업데이트 해준다.
const encodeBase64 = () => {
try {
const encodedData = btoa(unescape(encodeURIComponent(originalText)));
setBase64Text(encodedData);
setError("");
} catch (e) {
setError("Encoding failed. Please check the input.");
setBase64Text("Encoding failed. Please check the input.");
}
};
const decodeBase64 = () => {
try {
const decodedData = decodeURIComponent(escape(atob(base64Text)));
setOriginalText(decodedData);
setError("");
} catch (e) {
setError("Decoding failed. Please check if your input is valid base64.");
setOriginalText("Decoding failed. Please check if your input is valid base64.");
}
};
함수 그대로 람다로 사용하여 인코딩/디코딩하는 함수.
btoa만 쓰면 한글 입력시 예외 발생이지만 URI 인코딩해서 base64로 바꿀 수도 있다.
핵심은 디코딩할 때 형식이 까다롭기 때문에 예외발생 가능성이 높다.
base64원리가 궁금하다면 다음 포스팅을 참고.
https://codcost.tistory.com/98
[Cryptography] Base64 파헤치기
개념 우선, 위키백과의 사전 정의를 보면 컴퓨터 분야에서 쓰이는 Base란 6비트 이진 데이터(예를 들어 실행 파일이나, ZIP 파일 등)를 문자 코드에 영향을 받지 않는 공통 ASCII 영역의 문자들로만
codcost.tistory.com
코드설명: NextUI
</ Textaea>
<Textarea
label="Original Text"
placeholder="Enter text to encode..."
onChange={handleEncodeChange}
value={originalText}
variant="bordered"
fullWidth
minRows={30}
maxRows={30}
color="secondary"
/>
https://nextui.org/docs/components/textarea
npx nextui-cli@latest add input
| fullWidth: width 꽉채움.
| minRows={30}: textarea 최소 높이로,고정 높이라고 생각하면 됌.
| maxRows={30}: textarea에서 텍스트 초과 시 연장되는 길이.
Attribute에 대해서는 문서 아래에 설명되어 있다.
</ Textaea>
<Button onClick={encodeBase64} color="secondary" auto fullWidth>
Encode
</Button>
https://nextui.org/docs/components/button
크게 설명할 부분이 없어 보인다.
있는 그대로 읽으면 될 것.
globals.css
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--foreground-rgb: 40, 40, 40;
--background-start-rgb: 40, 40, 40;
--background-end-rgb: 40, 40, 40;
}
/* 기존의 dark mode 설정 */
@media (prefers-color-scheme: dark) {
:root {
--foreground-rgb: 200, 200, 200; // 폰트색
--background-start-rgb: 30, 30, 30;
--background-end-rgb: 40, 40, 40;
}
}
body {
color: rgb(var(--foreground-rgb));
background: linear-gradient(
to bottom,
rgb(var(--background-start-rgb)),
rgb(35, 35, 35) 50%,
rgb(var(--background-end-rgb))
);
}
@layer utilities {
.text-balance {
text-wrap: balance;
}
}
prefers-color-scheme: dark을 통해 body의 다크모드 색을 조절할 수 있다.
github 배포
https://velog.io/@yzii/Github-Pages%EB%A1%9C-Next-%ED%98%B8%EC%8A%A4%ED%8C%85
Github Pages로 Next 호스팅
깃헙에서 제공하는 정적 웹사이트 호스팅 서비스깃헙으로 프로젝트를 진행중이라면 레포지토리를 통해 손쉽게 웹사이트를 호스팅할 수 있다.나같은 경우는 Next로 프로젝트를 진행 중인데, 백
velog.io
이 페이지를 참조했다. (잘 나와있음)
'Software Framework > Next.js' 카테고리의 다른 글
[Next.js] FAST API에서 NextJS로 json 보내기 (0) | 2024.05.24 |
---|