0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React】グローバルCSSを導入する方法

Posted at

今回はReactプロジェクトに外部CSSを読み込む方法について記載します。
React(特に Vite / CRA / Next.js)での 外部 CSS の正しい置き場所
グローバル CSS か、コンポーネント限定 CSS か」で決まります。

用途 置き場所
リセット / 共通スタイル src/index.css / src/main.css normalize, reset
file input など全体影響 ssrc/styles/global.css 擬似要素
コンポーネント専用 同階層 or CSS Modules FileField.module.css
Atomic Design atoms atoms/*.module.css Input.module.css

①グローバル CSS(今回のケース:必須)

file input の ::file-selector-button

これは グローバル CSS に書くべきです。

典型構成(Vite)

src/
 ├ main.tsx
 ├ index.css   ← グローバル
 ├ styles/
 │   └ global.css
 └ components/

読み込みはmain.tsx

main.tsx
// main.tsx
import "./styles/global.css";

コンポーネント専用 CSSの場合

src/components/molecules/
 ├ FileField.tsx
 └ FileField.module.css
Sample.tsx
import styles from "./FileField.module.css";

<input className={styles.input} type="file" />

実装

今回は、グローバルCSSの導入です。
まずは、cssの導入から作っていきましょう。
src配下にstylesフォルダを作成しましょう。

src/styles/global.css
/* src/styles/global.css */
input[type="file"]::file-selector-button {
  appearance: auto;
  -webkit-appearance: auto;
  background-color: #e0e0e0;
  border: 1px solid #ccc;
  padding: 6px 12px;
}

つぎに、このglobal.cssの読み込みが1回だけ行われるようにmain.tsxに追加します。

src/main.tsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
import "./styles/global.css"//追加

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <App />
  </StrictMode>,
)

サイト

【React】Atmic designでFileアップロード機能を実装する

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?