보완 및 추가된 내용:

  • 비디오 로딩이 끝날 때까지 로딩 스피너 표시 (UX 개선)
  • 비디오 파일이 없거나 로드 실패 시 폴백 이미지 표시 (에러 처리)
  • 스타일 개선 (조금 더 깔끔한 디자인을 위해 세부적 스타일링 추가)
  • 타입 안정성 확보 (PropTypes 추가)
  • 유지보수 및 가독성 향상 (리팩토링)

 

src/components/VideoBackground.jsx

import React, { useState } from 'react';
import PropTypes from 'prop-types';

const VideoBackground = ({ videoSrc, fallbackImage, overlayText }) => {
  const [isVideoLoaded, setIsVideoLoaded] = useState(false);
  const [isError, setIsError] = useState(false);

  return (
    <div className="relative w-full h-screen overflow-hidden">
      {!isVideoLoaded && !isError && (
        <div className="absolute inset-0 bg-black flex items-center justify-center z-20">
          <div className="loader animate-spin rounded-full h-12 w-12 border-t-4 border-white"></div>
        </div>
      )}

      {isError ? (
        <img
          src={fallbackImage}
          alt="Background fallback"
          className="absolute top-0 left-0 w-full h-full object-cover z-0"
        />
      ) : (
        <video
          autoPlay
          loop
          muted
          playsInline
          className={`absolute top-0 left-0 w-full h-full object-cover z-0 transition-opacity duration-1000 ${isVideoLoaded ? 'opacity-100' : 'opacity-0'}`}
          onLoadedData={() => setIsVideoLoaded(true)}
          onError={() => setIsError(true)}
        >
          <source src={videoSrc} type="video/mp4" />
          브라우저가 비디오를 지원하지 않습니다.
        </video>
      )}

      <div className="absolute inset-0 z-10 flex items-center justify-center bg-black bg-opacity-50 text-white">
        <h1 className="text-4xl md:text-5xl font-bold shadow-lg">
          {overlayText}
        </h1>
      </div>
    </div>
  );
};

VideoBackground.propTypes = {
  videoSrc: PropTypes.string.isRequired,
  fallbackImage: PropTypes.string.isRequired,
  overlayText: PropTypes.string,
};

VideoBackground.defaultProps = {
  overlayText: '안녕하세요 반갑습니다!',
};

export default VideoBackground;

 

사용 예시 (src/App.jsx에 적용하기)

import React from 'react';
import VideoBackground from './components/VideoBackground';
import { motion, useScroll } from 'framer-motion';
import Header from './components/Header';
import Hero from './components/Hero';
import About from './components/About';
import ServicesSection from './components/ServicesSection';
import StatsSection from './components/StatsSection';
import ProjectGallery from './components/ProjectGallery';
import BlogSlider from './components/BlogSlider';
import SimpleCounter from './components/SimpleCounter';
import SimpleTodo from './components/SimpleTodo';
import SimpleCalculator from './components/SimpleCalculator';
import ThreeDPortfolio from './components/ThreeDPortfolio';
import AvatarPortfolio from './components/AvatarPortfolio';
import ParticlePortfolio from './components/ParticlePortfolio';
import Contact from './components/Contact';

function App() {
  const { scrollYProgress } = useScroll();

  return (
    <>
      <motion.div
        id="scroll-indicator"
        style={{
          scaleX: scrollYProgress,
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          height: '10px',
          backgroundColor: '#ff0088',
          zIndex: 9999,
          transformOrigin: '0% 50%',
        }}
      />

      <div style={{ minHeight: '200vh' }}>
        <VideoBackground
          videoSrc="/videos/intro.mp4"
          fallbackImage="/images/fallback.jpg"
          overlayText="환영합니다! 멋진 페이지에 오신 걸 환영해요!"
        />
        <Header />
        <Hero />
        <About />
        <ServicesSection />
        <StatsSection />
        <ProjectGallery />
        <BlogSlider />
        <SimpleCounter />
        <SimpleTodo />
        <SimpleCalculator />
        <ThreeDPortfolio />
        <AvatarPortfolio />
        <ParticlePortfolio />
        <Contact />
      </div>
    </>
  );
}

export default App;

 

Tailwind CSS 스타일링 추가하기 (tailwind.config.js에 다음을 추가)

 

// tailwind.config.js
module.exports = {
  // 생략
  theme: {
    extend: {
      animation: {
        spin: 'spin 1s linear infinite',
      },
      keyframes: {
        spin: {
          to: { transform: 'rotate(360deg)' },
        },
      },
    },
  },
};

 

추가 설명:

  • 로딩 스피너: 동영상이 로딩되는 동안 사용자가 지루하지 않도록 UX 개선.
  • 폴백 이미지: 영상이 로드되지 않거나 파일이 존재하지 않을 경우를 대비해 이미지 제공으로 오류 화면 방지.
  • Props 활용: VideoBackground 컴포넌트를 재사용 가능하게 만들어 다양한 영상 및 텍스트 지원 가능.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

질문:스타일컴포넌트 쓰다가 너무불편해서 모듈로 바꾸려고하는데 타입스크립트가 계속 모듈파일을 못읽네요.

1. typescript-plugin-css-modules 인스톨
2. declare module "*.module.css"; 선언

3. tsconfig 파일에 컴파일러옵션에     "plugins": [{ "name": "typescript-plugin-css-modules" }] 추가

 

강사님의 추천 안:

가끔은 설정 문제가 아닌 VSCode TS 서버가 오작동하는 경우도 있더라구요
ctrl + shift + p 누르신 다음 "TS 서버 다시시작"도 한번 진행해보세용.

 

수강생1 추천:

src 바로 밑에 global.d.ts 만드시고 
declare module "*.scss" {
  const content: { [className: string]: string };
  export = content;
}

내용 넣어줘보세요.

 

수강생2 추천:

https://velog.io/@dyorong/ts

 

[typescript] import './App.module.css' 에러 해결

'./App.module.scss' 모듈 또는 해당 형식 선언을 찾을 수 없습니다.

velog.io

 

ChatGPT 3.5 

답:

It sounds like you're encountering issues setting up CSS modules in your React + TypeScript project. Let's go through some troubleshooting steps to see if we can resolve this:

React + TypeScript 프로젝트에서 CSS 모듈을 설정하는 데 문제가 발생한 것 같습니다. 이 문제를 해결할 수 있는지 알아보기 위해 몇 가지 문제 해결 단계를 살펴보겠습니다.

  1. Ensure Proper Installation:  적절한 설치를 확인해보세요.
    • Make sure you've installed typescript-plugin-css-modules correctly. You can do this by running:
    • typescript-plugin-css-modules를 올바르게 설치했는지 확인하세요. 다음을 실행하여 이 작업을 수행할 수 있습니다. 
    • cssnpm install typescript-plugin-css-modules --save-dev
    • Double-check that it's listed in your package.json as a devDependency.
    • package.json에 devDependency로 나열되어 있는지 다시 확인하세요.
  2. Check TypeScript Configuration: TypeScript 구성을 확인하세요.
    • Confirm that you've added the appropriate declaration for CSS modules in your tsconfig.json file:
    • tsconfig.json 파일에 CSS 모듈에 대한 적절한 선언을 추가했는지 확인하세요.
    • json{ 
                "compilerOptions": { 
                ... 
                "plugins": [{ "name": "typescript-plugin-css-modules"}] 
                   } 
              }
    • Ensure there are no typos or syntax errors in your tsconfig.json.
    • tsconfig.json에 오타나 구문 오류가 없는지 확인하세요.
  3. Verify File Naming Convention: 파일 명명 규칙 확인:
    • CSS modules typically use the .module.css file extension. Ensure that your CSS files follow this convention (e.g., styles.module.css).
    • CSS 모듈은 일반적으로 .module.css 파일 확장자를 사용합니다. CSS 파일이 이 규칙(예: styles.module.css)을 따르는지 확인하세요.
  4. Check File Paths: 파일 경로 확인
    • Confirm that your CSS module files are located in the same directory or a subdirectory relative to the components that use them.
    • CSS 모듈 파일이 해당 파일을 사용하는 구성 요소와 동일한 디렉터리 또는 하위 디렉터리에 있는지 확인하세요.
    • Verify that the file paths in your import statements are correct.
    • 가져오기 문의 파일 경로가 올바른지 확인하세요.
  5. Restart Development Server: 개발 서버를 다시 시작합니다.
    • Sometimes, changes to TypeScript configuration or plugin installation may require restarting your development server for the changes to take effect. Try stopping and restarting your development server.
    • 경우에 따라 TypeScript 구성 또는 플러그인 설치를 변경하면 변경 사항을 적용하기 위해 개발 서버를 다시 시작해야 할 수도 있습니다. 개발 서버를 중지했다가 다시 시작해 보세요.
  6. Check for Errors in Development Console: 개발 콘솔에서 오류 확인
    • Inspect your browser's console for any error messages related to CSS module imports. This can provide valuable clues about what might be going wrong.
    • CSS 모듈 가져오기와 관련된 오류 메시지가 있는지 브라우저 콘솔을 검사하세요. 이는 무엇이 잘못될 수 있는지에 대한 귀중한 단서를 제공할 수 있습니다.
  7. Test with a Simple Example: 간단한 예제로 테스트
    • Create a minimal example component and corresponding CSS module to see if you can get CSS modules working in isolation. This can help isolate whether the issue is specific to certain components or configurations.
    • 최소한의 예제 구성 요소와 해당 CSS 모듈을 만들어 CSS 모듈이 독립적으로 작동할 수 있는지 확인하세요. 이를 통해 문제가 특정 구성 요소나 구성에만 국한되는지 파악하는 데 도움이 됩니다.
  8. Seek Help from Community: 커뮤니티에서 도움을 구하세요:
    • If you've tried everything and still can't resolve the issue, consider seeking help from online communities like Stack Overflow or forums dedicated to React and TypeScript development. Sometimes, others may have encountered similar problems and can offer valuable insights.
    • 모든 방법을 시도했지만 여전히 문제를 해결할 수 없다면 Stack Overflow와 같은 온라인 커뮤니티나 React 및 TypeScript 개발 전용 포럼에서 도움을 구하는 것이 좋습니다. 때로는 다른 사람들도 비슷한 문제를 겪었을 수 있으며 귀중한 통찰력을 제공할 수 있습니다.

By systematically going through these steps, you should be able to identify and resolve the issue with CSS modules in your React + TypeScript project. Let me know if you need further assistance with any specific step!

이러한 단계를 체계적으로 진행하면 React + TypeScript 프로젝트의 CSS 모듈 문제를 식별하고 해결할 수 있습니다. 특정 단계에서 추가 지원이 필요한 경우 알려주시기 바랍니다!

 

질문자 본인 수정결과:

 

global.d.ts 파일에 꼭 넣어야 되는거였네요 .

 

추가로 참고사항:

https://nextjs.org/docs/app/building-your-application/routing/route-handlers

 

Routing: Route Handlers | Next.js

Create custom request handlers for a given route using the Web's Request and Response APIs.

nextjs.org

 

 

React.StrictMode 와 BrowserRouter 가 서로를 감쌀때 기능적으로 어떤 변화가 있는가?

기능1:

<React.StrictMode>
  <BrowserRouter>
    <App /> 
  </BrowserRouter>
</React.StrictMode>

 

기능2:

<BrowserRouter>
    <React.StrictMode>
        <App />
    </React.StrictMode>
</BrowserRouter>

 

The two snippets you provided represent two different approaches to structuring a React application with React Router (BrowserRouter) and React.StrictMode. Let's examine each:
귀하가 제공한 두 조각은 React Router(BrowserRouter) 및 React.StrictMode를 사용하여 React 애플리케이션을 구성하는 두 가지 서로 다른 접근 방식을 나타냅니다. 각각을 살펴보겠습니다:

1.<React.StrictMode> outside <BrowserRouter>:
<BrowserRouter> 외부의 <React.StrictMode>:

<React.StrictMode>
  <BrowserRouter>
    <App /> 
  </BrowserRouter>
</React.StrictMode>

In this setup, React.StrictMode wraps the entire application including the router. StrictMode is a tool for highlighting potential problems in an application. It activates additional checks and warnings for its descendants. By placing StrictMode at the top, it ensures that these checks are applied to all parts of the app, including the routing logic.
이 설정에서 React.StrictMode는 라우터를 포함한 전체 애플리케이션을 래핑합니다. StrictMode는 응용 프로그램의 잠재적인 문제를 강조하기 위한 도구입니다. 해당 하위 항목에 대한 추가 확인 및 경고를 활성화합니다. StrictMode를 맨 위에 배치하면 라우팅 논리를 포함하여 앱의 모든 부분에 이러한 검사가 적용됩니다.

 

2.<BrowserRouter> outside <React.StrictMode>:
<React.StrictMode> 외부의 <BrowserRouter>:

<BrowserRouter>
    <React.StrictMode>
        <App />
    </React.StrictMode>
</BrowserRouter>

 

In this structure, the router is outside of StrictMode. This means that StrictMode checks will not be applied to the router itself, only to the components inside App.
이 구조에서 라우터는 StrictMode 외부에 있습니다. 즉, StrictMode 검사는 라우터 자체에는 적용되지 않고 앱 내부 구성 요소에만 적용됩니다.

 

Which is More Accurate?

어느 것이 더 정확합니까?

 

Both configurations are valid, but they have slightly different implications:
두 구성 모두 유효하지만 의미가 약간 다릅니다.

1.If you want StrictMode checks to apply to the router as well, the first approach is preferable. This ensures that all parts of your application, including routing, are subject to StrictMode's checks.
StrictMode 검사를 라우터에도 적용하려면 첫 번째 접근 방식이 더 좋습니다. 이렇게 하면 라우팅을 포함한 애플리케이션의 모든 부분이 StrictMode의 검사를 받게 됩니다.

2.If you are only concerned with applying StrictMode to your own components (i.e., everything inside App), and not to the routing logic, the second approach works fine.
StrictMode를 라우팅 논리가 아닌 자체 구성 요소(즉, 앱 내부의 모든 것)에만 적용하는 데 관심이 있다면 두 번째 접근 방식이 제대로 작동합니다.

 

In general, the first approach is often recommended because it provides a more comprehensive coverage of StrictMode checks across your entire application, including the routing logic. However, the choice can depend on specific needs or preferences in how you want to structure your application and what parts you want to be scrutinized by StrictMode.
일반적으로 첫 번째 접근 방식은 라우팅 논리를 포함하여 전체 애플리케이션에 걸쳐 StrictMode 검사에 대한 보다 포괄적인 적용 범위를 제공하므로 권장되는 경우가 많습니다. 그러나 선택은 애플리케이션을 구성하려는 방식과 StrictMode에서 면밀히 조사하려는 부분에 대한 특정 요구 사항이나 선호도에 따라 달라질 수 있습니다.

 

참고사항:

https://noah-dev.tistory.com/38

 

React Router v6.4 이상에서 Router 다루기(RouterProvider, createBrowserRouter, Route)

들어가기 전 21년 말, react-router-dom을 사용할 땐 v6.3이었다. 현재는 메이저 버전은 동일하지만 v6.4를 기점으로 기존에 없던 새로운 기능이 추가되어 이를 소개하고자 한다. 아래의 사진에서 보는

noah-dev.tistory.com

React Router v6 설치하기

https://velog.io/@sparkling0_0/2.-React-Routerv6-사용하기

 

velog

 

velog.io

 

 

 

 

질문이 있는데 useEffect에서 [post]로 하면 무한 루프가 돌고 저런식으로 [boardSetData,post.postId,post.nttSj,post.nttCn] 으로 놓으면 무한루프가 돌지 않는데 이유를 알수 있을까요 ...

postId는 글번호 nttSj 제목 , nttCn 제목이며
const boardSetData = useContext(BbsSettingContext);
여기서 boardSetData는 게시판 셋팅 데이터 입니다 .왜 무한 루프가 도는지 알수있을까요 .

게시판 셋팅 , 글제목, 글번호 글내용이 바뀌면 useEffect의 axios가 전송 되어야 하게 할려고 합니다 근데 무한 루프가 도네요 ...

import React, { useState, useEffect, useContext, useRef } from "react";
import { useNavigate } from "react-router-dom";

import axios from "axios";
import { BbsSettingContext } from "../common/Board";
import ToastEditor from "../component/ToastEditor";
import MyButton from "../common/ComButton";

const BoardView = ({ postId }) => {
  const titleInputRef = useRef();
  const contentsAreaRef = useRef();
  const toastEditorRef = useRef(); // ToastEditor의 ref

  const [post, setPost] = useState({
    nttSj: "",
    nttCn: "",
    regDate: "",
  });
  const [boardSetting, setBoardSetting] = useState(null);
  const boardSetData = useContext(BbsSettingContext);
  const Navigate = useNavigate();
  const formatDate = (timestamp) => {
    const date = new Date(timestamp);
    const options = { year: "numeric", month: "long", day: "numeric" };
    return date.toLocaleDateString("ko-KR", options);
  };

  useEffect(() => {
    if (boardSetData) {
      setBoardSetting(boardSetData);
      axios
        .get(`http://localhost:8080/board/${boardSetData.bbsId}/post/${postId}`)
        .then((response) => {
          setPost({
            nttSj: response.data.post.nttSj,
            nttCn: response.data.post.nttCn,
            regDate: response.data.post.regDate,
          });
        })
        .catch((error) => console.log(error));
    }
  }, [post]);
  return (
    <div className="BoardView">
      <div className="upInfoArea">
        <div type="text" name="boardTitle" className="titleDiv">
          {post.nttCn}
        </div>
        <div type="text" name="regId" className="regIdDIv">
          {formatDate(post.regDate)}
        </div>
      </div>
      <div className="contentArea">
        <div className="contentsText">{post.nttCn}</div>
      </div>
      <section>
        <div className="btnArea">
          <MyButton text={"리스트이동"} onClick={() => Navigate(-1)} />
          <MyButton text={"수정하기"} type="positive" />
        </div>
      </section>
    </div>
  );
};

export default BoardView;

 

 

The infinite loop in your useEffect hook is caused by the way you've set its dependency array and the state update logic inside the hook. Let's break down what's happening:

1.Dependency Array with "[post]": When you use "[post]" as a dependency array, it means the "useEffect" hook will run every time the "post" object changes.

2.State Update Inside "useEffect": Inside this "useEffect", you're making an axios call that eventually updates the "post" state with "setPost".

 

Here's the cycle that causes the infinite loop:

1."useEffect" runs because post changes.

2.Inside "useEffect", an axios call is made.

3.The axios call completes and updates the "post" state with "setPost".

4.The update of the "post" state triggers the "useEffect" again (because "post" is in the dependency array).

5.This cycle repeats indefinitely.

 

Dependency Array with [boardSetData, postId, post.nttSj, post.nttCn]: When you change the dependency array to [boardSetData, postId, post.nttSj, post.nttCn], the useEffect only runs when:

1."boardSetData" changes (which presumably doesn't happen often or as a result of the axios call).

2."postId" changes (which likely only happens when navigating to a different post).

3."post.nttSj" (title) changes.

4.post.nttCn (content) changes.

 

Since the useEffect is not directly updating any of these dependencies, it doesn't trigger itself repeatedly.

 

Recommendation:

To prevent the infinite loop, ensure that the useEffect hook does not update any of the values in its dependency array. In your case, using [boardSetData, postId, post.nttSj, post.nttCn] is the correct approach because you want the useEffect to run when the bulletin board settings or the specific details of the post change, but not every time the post object is updated in any way. This prevents the axios call from triggering a state update that would cause the useEffect to run again, thereby avoiding the infinite loop.

 

useEffect 후크의 무한 루프는 종속성 배열과 후크 내부의 상태 업데이트 논리를 설정한 방식으로 인해 발생합니다. 무슨 일이 일어나고 있는지 분석해 보겠습니다.

1.[post]를 사용한 종속성 배열: [post]를 종속성 배열로 사용하면 post 개체가 변경될 때마다 useEffect 후크가 실행된다는 의미입니다.

2.useEffect 내부의 상태 업데이트: 이 useEffect 내부에서는 결국 setPost를 사용하여 게시 상태를 업데이트하는 axios 호출을 만들고 있습니다.

 

무한 루프를 일으키는 사이클은 다음과 같습니다.

1.게시물이 변경되어 useEffect가 실행됩니다.

2.useEffect 내부에서 axios 호출이 이루어집니다.

3.axios 호출은 setPost를 사용하여 게시 상태를 완료하고 업데이트합니다.

4.post 상태가 업데이트되면 useEffect가 다시 트리거됩니다(post가 종속성 배열에 있기 때문입니다).

5.이 주기는 무한정 반복됩니다.

 

[boardSetData, postId, post.nttSj, post.nttCn]을 사용한 종속성 배열: 종속성 배열을 [boardSetData, postId, post.nttSj, post.nttCn]으로 변경하면 useEffect는 다음 경우에만 실행됩니다.

1.BoardSetData 변경 사항(아마도 자주 발생하지 않거나 axios 호출의 결과로 발생함)

2.postId 변경(다른 게시물로 이동할 때만 발생할 수 있음)

3.post.nttSj(제목)이 변경됩니다.

4.post.nttCn(콘텐츠)이 변경됩니다.

 

useEffect는 이러한 종속성을 직접 업데이트하지 않으므로 자체적으로 반복적으로 트리거되지 않습니다.

 

추천:

무한 루프를 방지하려면 useEffect 후크가 종속성 배열의 값을 업데이트하지 않는지 확인하세요. 귀하의 경우에는 [boardSetData, postId, post.nttSj, post.nttCn]을 사용하는 것이 올바른 접근 방식입니다. 왜냐하면 게시판 설정이나 게시물의 특정 세부 사항이 변경될 때 useEffect를 실행하기를 원하기 때문입니다. 그러나 게시물 개체가 변경될 때마다 실행되는 것은 아닙니다. 어떤 방식으로든 업데이트됩니다. 이는 axios 호출이 useEffect를 다시 실행하게 하는 상태 업데이트를 트리거하는 것을 방지하여 무한 루프를 방지합니다.

Angular에서 AuthGuard는 사용자 인증 및 권한 부여를 기반으로 경로에 대한 액세스를 제어하는 ​​일반적인 메커니즘입니다. AuthGuard 자체는 로그인 또는 등록 기능을 직접 처리하지 않지만 인증되지 않은 액세스 또는 무단 액세스로부터 특정 경로를 보호하기 위해 이러한 기능과 함께 사용되는 경우가 많습니다.

 

다음은 Angular에서 AuthGuard를 설정하는 방법에 대한 간략한 개요입니다.

 

1.AuthGuard 서비스 만들기:

경로 활성화 또는 지연 로드 경로를 각각 보호할지 여부에 따라 CanActivate 또는 CanLoad 인터페이스를 구현하는 AuthGuard 서비스를 만듭니다.

 

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(): boolean {
    // Here, you'd typically check some authentication service or token
    // For simplicity, let's assume we're checking a boolean flag
    if (/* user is authenticated */) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

2.라우팅 구성에서 AuthGuard 사용:

AuthGuard 서비스가 정의되면 라우팅 구성에서 이를 사용하여 특정 경로를 보호할 수 있습니다.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './auth.guard';

const routes: Routes = [
  { path: 'protected', component: ProtectedComponent, canActivate: [AuthGuard] },
  // ... other routes
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

3.실제 인증 메커니즘과 통합:

위의 예는 매우 단순화되었습니다. 실제 애플리케이션에서 AuthGuard는 인증 토큰의 존재와 유효성을 확인하는 인증 서비스 또는 사용자가 인증되었는지 여부를 결정하는 다른 메커니즘과 통합될 가능성이 높습니다.

 

4.역할 기반 액세스 제어(RBAC) 처리:

서로 다른 사용자가 서로 다른 역할을 갖고 있는 경우 AuthGuard 메커니즘을 확장하여 사용자가 인증되었는지 여부뿐만 아니라 특정 경로에 액세스하는 데 필요한 권한이나 역할이 있는지도 확인할 수 있습니다.

 

결론적으로 AuthGuard는 로그인 또는 등록 프로세스를 직접적으로 담당하지는 않지만 인증된(그리고 권한이 있는) 사용자만 Angular 애플리케이션의 특정 경로에 액세스할 수 있도록 하는 데 필수적인 역할을 합니다

'React' 카테고리의 다른 글

질문답변 2024-01-27 React Router  (2) 2024.01.27
왜? 무한루프가 도는지?  (0) 2023.11.12
<table> 태그에서, 테이블에서 원하는 테두리 반경 효과  (2) 2023.08.29
CSS Grid Layout example  (2) 2023.04.15
Menus CSS  (0) 2023.04.01

 

다음은 테이블에서 원하는 테두리 반경 효과를 얻는 데 도움이 되는 단계별 가이드입니다.

1.테이블을 div로 감싸고 div에 border-radius를 적용합니다.

이것이 당신이 한 일이라고 언급한 일인데, 좋은 시작입니다. 오버플로 설정: 내부 테이블이 곡선 가장자리 위로 넘치지 않도록 div에 숨겨집니다.

.table-wrapper {
    border-radius: 15px;
    overflow: hidden;
}

2.테이블 자체에서 테두리를 제거합니다.

이렇게 하면 표 셀의 테두리가 래핑 div의 테두리 반경을 방해하지 않습니다.

table {
    border-collapse: collapse;
    border: none;
}

3.배경색을 처리합니다.

테이블(th 및 td 요소)에 배경색이 있는 경우에도 여전히 래핑 div의 테두리 반경 너머에 표시됩니다. 이를 처리하기 위해 의사 요소를 사용할 수 있습니다.

먼저 테이블 셀의 배경색을 조정합니다.

table th, table td {
    background-color: transparent;
}

그런 다음 의사 요소를 사용하여 배경색을 설정합니다.

.table-wrapper::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: -1;
    background-color: YOUR_COLOR;  /* Replace with your table's background color */
    border-radius: inherit;
}

그리고 래퍼에 상대 위치를 지정합니다.

.table-wrapper {
    position: relative;
    /* ... other styles ... */
}

4.표 머리글 및 바닥글 그룹:

테이블에 <thead> 및/또는 <tfoot>이 있는 경우 모서리가 테두리 반경을 따르지 않을 수 있습니다. 이 문제를 해결하려면 첫 번째 셀과 마지막 셀에 border-radius를 직접 적용하면 됩니다.

<thead>가 있는 테이블의 경우:

table thead th:first-child {
    border-top-left-radius: 15px;
}

table thead th:last-child {
    border-top-right-radius: 15px;
}

그리고 <tfoot>이 있는 테이블의 경우:

table tfoot td:first-child {
    border-bottom-left-radius: 15px;
}

table tfoot td:last-child {
    border-bottom-right-radius: 15px;
}

이러한 조정을 통해 테이블은 테두리 반경을 준수하고 예상대로 표시되어야 합니다. 디자인에 필요에 따라 값을 조정합니다.

 

th,td에 각 색깔이 다른데 이경우에도 위에처럼 적용하면 가능할까요?

*각 th와 td의 배경색이 다른 경우 배경에 단일 의사 요소를 사용하는 위의 솔루션은 의도한 대로 작동하지 않습니다. 이 경우 포함된 div의 둥근 모서리를 따르도록 테이블의 th 및 td 요소에 border-radius를 직접 적용해야 합니다.

1.테이블을 div로 감싸고 이미 div로 감싼 상태라면 div에 Overflow:Hidden이 있는지 확인하세요.

.table-wrapper {
    border-radius: 15px;
    overflow: hidden;
}

2.테이블 자체에서 테두리를 제거합니다.

table {
    border-collapse: collapse;
    border: none;
}

3.첫 번째와 마지막 th 및 td에 border-radius를 적용합니다.

테이블의 왼쪽 및 오른쪽 상단 모서리의 경우:

table th:first-child, table tr:first-child td:first-child {
    border-top-left-radius: 15px;
}

table th:last-child, table tr:first-child td:last-child {
    border-top-right-radius: 15px;
}

테이블의 왼쪽 하단과 오른쪽 모서리에 대해(마지막 행이 td 요소로 구성되어 있다고 가정):

table tr:last-child td:first-child {
    border-bottom-left-radius: 15px;
}

table tr:last-child td:last-child {
    border-bottom-right-radius: 15px;
}

이제 각 th와 td의 배경색이 다르더라도 포함된 div의 둥근 모서리를 존중합니다. 이 접근 방식은 th 및 td 요소에 테두리가 없거나 테두리가 일관적일 때 예상치 못한 시각적 결과를 피하기 위해 가장 잘 작동합니다.

 

마지막으로 테이블 디자인, 패딩 및 기타 CSS 속성에 따라 테두리 반경 값을 약간 조정해야 할 수도 있습니다.

css grid layout example

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout

 

CSS Grid Layout - CSS: Cascading Style Sheets | MDN

CSS Grid Layout excels at dividing a page into major regions or defining the relationship in terms of size, position, and layer, between parts of a control built from HTML primitives.

developer.mozilla.org

 

https://www.w3schools.com/css/css_grid.asp

 

CSS Grid Layout

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

example 1

https://nykim.work/59

 

[CSS] CSS Grid (그리드) 배우기

프롤로그 레이아웃을 구현할 때 flexbox를 쓰면 참 편합니다. 플박만으로 레이아웃을 구현하는 데 큰 문제는 없지만, 보다 정교하고 복잡한 레이아웃에는 그리드가 좋다는 소문(?)을 들었거든요.

nykim.work

example2

https://gridbyexample.com/examples/

 

Grid by Example - Usage examples of CSS Grid Layout

The following examples include an image of how the example should look in a supporting browser, they each link to a page with more information about the technique being shown, code and a CodePen of the example. Unless otherwise noted these examples work in

gridbyexample.com

example3

https://blog.devgenius.io/how-to-use-css-grid-layout-including-a-react-example-ea67455e902b

 

How to use CSS grid layout including a react example

To arrange your element precisely

blog.devgenius.io

example4

https://betterprogramming.pub/css-grid-in-react-f8323b521fab

 

CSS GRID — In React

A powerful tool for creating a two-dimensional grid system using rows and columns

betterprogramming.pub

example5

https://armadillo-dev.github.io/css/understanding-grid-layout/

 

[CSS] Grid layout 이해하기

Grid layout은 Flexbox와 마찬가지로, 레이아웃을 보다 수월하게 구성할 수 있도록 도와준다. 특히 열과 행으로 구성된 레이아웃에 탁월함을 보인다. 이 글에서는 Grid layout에 대해 설명하고, 예제를

armadillo-dev.github.io

example6

https://css-tricks.com/snippets/css/complete-guide-grid/

 

A Complete Guide to CSS Grid | CSS-Tricks

Our comprehensive guide to CSS grid, focusing on all the settings both for the grid parent container and the grid child elements.

css-tricks.com

 

list-style: none; /* 항목 표시가 되지 않음 */

disc : 기본값, 검은 원
circle : 원
square 사각형
decimal : 숫자(1로 시작하는 십진수)
lower-alpha  : 알파벳 소문자 (a, b, c, d, e,..)
lower-roman : 로마자 소문자 (i, ii, iii, iv, v,..)
upper-alpha : 알파벳 대문자 (A, B, C, D, E...)
upper-roman :  로마자 대문자 (I, II, III, IV, V,...)
none : 항목 표시가 되지 않음
initial  : 기본값으로 초기화

 

display:block; /* 요소를 block 요소처럼 표시한다. 따라서 요소 앞 뒤로 줄바꿈 된다 */

display:inline; /* 기본값, 요소 앞 뒤로 줄바꿈되지 않는다 */

display:none; /* 박스가 생성되지 않는다. 공간을 차지 하지 않는다 */

display:inline-block; /* 요소는 inline 인데 내부는 block 처럼 표시함. */

 

overflow : auto; /* 내용이 잘릴때만 스크롤바가 보인다 */

overflow : visible; /* 기본값으로 내용이 더 길어도 그대로 보인다 */

overflow : hidden; /* 내용이 넘치면 자른다. 자른 부분은 보이지 않는다 */

overflow : scroll; /* 내용이 넘치지 않아도 항상 스크롤바가 보인다 */

 

clear : float 를 해제할 때 사용한다.

clear : none /* 기본값으로 clear 를 설정하지 않는 것과 같다 */

clear : left   /* float:left 값을 취소한다. */

clear : right /* float:right 값을 취소한다. */

clear : both /* 왼쪽, 오른쪽을 취소한다 */

출처: https://link2me.tistory.com/1455 [소소한 일상 및 업무TIP 다루기:티스토리]

 

CSS Grid Layout

 

 

 

 



엑셀 다운로드 기능 구현

패키지설치

https://www.npmjs.com/package/xlsx

 

xlsx

SheetJS Spreadsheet data parser and writer. Latest version: 0.18.5, last published: a year ago. Start using xlsx in your project by running `npm i xlsx`. There are 3740 other projects in the npm registry using xlsx.

www.npmjs.com

https://kkhcode.tistory.com/12

 

React 엑셀 다운로드

내가 자주 사용하는 엑셀 파일로 다운로드를 하기위해 XLSX와 FileSaver를 다운받아야한다. XLSX는 복잡한 스프레드시트에서 유용한 데이터를 추출하고 새 스프레드시트를 생성하기 위해 검증된 오

kkhcode.tistory.com

 

 

React에서 엑셀뷰어

https://www.npmjs.com/package/react-spreadsheet

 

react-spreadsheet

Simple, customizable yet performant spreadsheet for React. Latest version: 0.7.8, last published: 17 days ago. Start using react-spreadsheet in your project by running `npm i react-spreadsheet`. There are 4 other projects in the npm registry using react-sp

www.npmjs.com

2.엑셀뷰어 예제

https://www.grapecity.com/wijmo/demos/Excel/WorkbookViewer/react

 

Workbook Viewer | Excel | React Wijmo Demos

import 'bootstrap.css'; import '@grapecity/wijmo.styles/wijmo.css'; import './app.css'; // import * as React from 'react'; import * as ReactDOM from 'react-dom/client'; import * as wjcCore from '@grapecity/wijmo'; import * as wjcXlsx from '@grapecity/wijmo

www.grapecity.com

@grapecity/wijmo 패키지 다운로드(설치하기)

https://www.npmjs.com/package/@grapecity/wijmo

 

@grapecity/wijmo

UI library for pure JS, Angular, React, Vue and more.... Latest version: 5.20222.877, last published: 3 months ago. Start using @grapecity/wijmo in your project by running `npm i @grapecity/wijmo`. There are 204 other projects in the npm registry using @gr

www.npmjs.com

@grapecity/wijmo.xlsx 패키지 설치하기

https://www.npmjs.com/package/@grapecity/wijmo.xlsx

 

@grapecity/wijmo.xlsx

UI library for pure JS, Angular, React, Vue and more.... Latest version: 5.20222.877, last published: 3 months ago. Start using @grapecity/wijmo.xlsx in your project by running `npm i @grapecity/wijmo.xlsx`. There are 6 other projects in the npm registry u

www.npmjs.com

npm i @grapecity/wijmo.styles 

패키지 설치하기

https://www.npmjs.com/package/@grapecity/wijmo.styles

 

https://getbootstrap.com/docs/4.0/getting-started/download/

 

Download

Download Bootstrap to get the compiled CSS and JavaScript, source code, or include it with your favorite package managers like npm, RubyGems, and more.

getbootstrap.com

npm install bootstrap

엑셀뷰어 예제1

https://www.grapecity.com/wijmo/demos/Excel/WorkbookViewer/react

 

Workbook Viewer | Excel | React Wijmo Demos

import 'bootstrap.css'; import '@grapecity/wijmo.styles/wijmo.css'; import './app.css'; // import * as React from 'react'; import * as ReactDOM from 'react-dom/client'; import * as wjcCore from '@grapecity/wijmo'; import * as wjcXlsx from '@grapecity/wijmo

www.grapecity.com

엑셀뷰어 예제2

https://codesandbox.io/examples/package/react-excel-renderer

 

react-excel-renderer examples - CodeSandbox

 

codesandbox.io

 

엑셀뷰어 구현하기에서 발생한 문제점들

Module not found: Error: Can't resolve './App.css' in '/Users/marshall-kim/Documents/React/taijiyuankrtwo/reactexample/src/Pages'

매번 에러가 발생할때마다 구글링하여 문제점을 하나하나 해결해나갔다.

1.bootstrap.css  존재하지 않는다는 에러가 발생하기에 https://getbootstrap.com/docs/4.0/getting-started/download/

사이트에 들어가서 Compiled CSS and JS를 다운로드하고 그 폴더안에 bootstrap.css 파일을 copy하여 갖다 붙혔다.

 

2.문제점

Failed to build project with JSZip library

이런 에러가 뜨기에 https://github.com/angular/angular-cli/issues/10625#issuecomment-390878516%E2%80%8B

 

Failed to build project with JSZip library · Issue #10625 · angular/angular-cli

Versions Angular CLI: 6.0.0 Node: 8.11.1 OS: win32 x64 Angular: 6.0.0 ... animations, cli, common, compiler, compiler-cli, core, forms ... http, language-service, platform-browser ... platform-brow...

github.com

이 사이트에 들어가서 아래의 패키지를 캡처하여 install 실행함

  • npm i --save jszip

3. 시스템의 요구에 의하여 Bootstrap version4.0 을 Bootstrap version 3.0으로 낮추어 다운받아 설치했다.

npm install bootstrap

npm install --save react-bootstrap bootstrap@3

 

코딩애플 블로그에 들어가서 벤치마킹하기도 하고 https://codingapple.com/forums/topic/failed-to-compile-오류가-해결이-되지-않습니다/

 

4. 컴포넌트 상단에 필요한 패키지즐을 찾아서 설치하였다

npm i @grapecity/wijmo.xlsx

 

React file viewer

https://github.com/plangrid/react-file-viewer/blob/master/src/components/drivers/xlsx-viewer.jsx

 

GitHub - plangrid/react-file-viewer

Contribute to plangrid/react-file-viewer development by creating an account on GitHub.

github.com

 

 

 

 

React Hooks

https://www.w3schools.com/react/react_useeffect.asp

 

React useEffect

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

 

useEffect의 dependency array 기능

https://velog.io/@commitnpush/useEffect의-dependency-array

 

useEffect의 dependency array

일반적으로 함수형 컴포넌트 내부에서 발생하는 side effect를 처리할 때 react 모듈에서 제공하는 useEffect함수를 사용한다. 이 때 두 번째 파라미터로 입력하는 dependency array에 의한 useEffect의 동작

velog.io

React Redux 사용하기

https://kyounghwan01.github.io/blog/React/redux/redux-basic/#사용하는-이유

 

react-redux 사용법, redux, react, react16, state management, flux, store, reducer, dispatch, action

react-redux 사용법, redux, react, react16, state management, flux, store, reducer, dispatch, action

kyounghwan01.github.io

 

 

 

 

 

 

+ Recent posts