「React、難しそう」と感じていませんか?
現役WEBエンジニアとして、Reactで開発しています。
この記事では、React初心者向けに基本を解説します。
目次
Reactとは
簡単に言うと
- Facebook製のUIライブラリ
- コンポーネントベース
- 仮想DOMで高速
なぜ人気なのか
| 理由 | 詳細 |
|---|---|
| 求人多い | 最も需要のあるライブラリ |
| エコシステム | ライブラリが豊富 |
| 学習リソース | 情報が多い |
| 再利用性 | コンポーネントで効率的 |
環境構築
Create React App(従来)
npx create-react-app my-app
cd my-app
npm start
Vite(推奨)
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
npm run dev
基本概念
コンポーネント
// 関数コンポーネント
function Welcome() {
return <h1>Hello, React!</h1>;
}
// アロー関数
const Welcome = () => {
return <h1>Hello, React!</h1>;
};
JSX
// JSXはHTMLっぽく書ける
function App() {
const name = "田中";
return (
<div>
<h1>こんにちは、{name}さん</h1>
<p>Reactを学んでいます</p>
</div>
);
}
Props
// 親コンポーネント
function App() {
return <Welcome name="田中" />;
}
// 子コンポーネント
function Welcome({ name }) {
return <h1>こんにちは、{name}さん</h1>;
}
フック(Hooks)
useState
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>カウント: {count}</p>
<button onClick={() => setCount(count + 1)}>
+1
</button>
</div>
);
}
useEffect
import { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(s => s + 1);
}, 1000);
// クリーンアップ
return () => clearInterval(interval);
}, []);
return <p>経過時間: {seconds}秒</p>;
}
イベント処理
function Form() {
const [text, setText] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
console.log(text);
};
return (
<form onSubmit={handleSubmit}>
<input
value={text}
onChange={(e) => setText(e.target.value)}
/>
<button type="submit">送信</button>
</form>
);
}
条件分岐とループ
条件分岐
function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? (
<p>ようこそ!</p>
) : (
<p>ログインしてください</p>
)}
</div>
);
}
ループ
function List({ items }) {
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
学習のコツ
ステップ
- JSXを理解する
- コンポーネントを作る
- useState を使う
- useEffect を使う
- 実際にアプリを作る
まとめ
React入門のポイント:
- コンポーネントの考え方
- JSXの書き方
- useState/useEffectを覚える
- 実際に作って学ぶ
