React HooksとContext APIを使用してCRUDアプリを構築する方法
紹介
この記事では、コンテキストAPI(バージョン16.3で導入)とReactフック(バージョン16.8で導入)について説明します。
Context APIの導入は、プロップのドリリングという1つの大きな問題を解決します。これは、ネストされた深いコンポーネントのレイヤーを通して、データを1つのコンポーネントから別のコンポーネントに渡すプロセスです。Reactフックを使用することで、クラスベースのコンポーネントではなく、関数型コンポーネントを使用できるようになります。ライフサイクルメソッドを利用する必要がある場合、クラスベースのアプローチを使用しなければなりませんでした。しかし、今ではsuper(props)を呼び出したり、メソッドのバインディングやthisキーワードについて心配する必要がありません。
この記事では、Context API と React フックを組み合わせて、従業員のリストを模倣する完全に機能する CRUD アプリケーションを構築します。このアプリケーションは、従業員データを読み取り、新しい従業員を作成し、従業員データを更新し、従業員を削除します。なお、このチュートリアルでは外部 API コールは使用しません。デモンストレーションのために、状態として機能するハードコーディングされたオブジェクトを使用します。
前提条件
このチュートリアルを完了するためには、次のものが必要です:
- Node.jsのローカル開発環境。Node.jsのインストール方法とローカル開発環境の作成方法に従ってください。
- インポート、エクスポート、およびReactコンポーネントのレンダリングに関する理解。私たちの「React.jsでのコーディング方法」シリーズをチェックしてみてください。
このチュートリアルは、Node v15.3.0、npm v7.4.0、react v17.0.1、react-router-dom v5.2.0、tailwindcss-cli v0.1.2、およびtailwindcss v2.0.2で確認されました。
ステップ1 — プロジェクトの設定
まず、次のコマンドを使用してCreate React AppでReactプロジェクトをセットアップします:
- npx create-react-app react-crud-employees-example
新しく作成されたプロジェクトディレクトリに移動します:
- cd react-crud-employees-example
次に、以下のコマンドを実行してreact-router-domを依存関係として追加します:
- npm install react-router-dom@5.2.0
注意:React Routerに関する追加情報は、私たちのReact Routerチュートリアルを参照してください。
次に、srcディレクトリに移動します:
cd src
次のコマンドを使って、プロジェクトにTailwind CSSのデフォルトビルドを追加してください:
- npx tailwindcss-cli@0.1.2 build --output tailwind.css
注意: Tailwind CSSに関する追加情報は、私たちのTailwind CSSチュートリアルを参照してください。
次に、コードエディタで index.js を開き、tailwind.css と BrowserRouter を使うように修正します:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import './tailwind.css';
import './index.css';
import App from './App';
ReactDOM.render(
<BrowserRouter>
<App />
<BrowserRouter>
document.getElementById('root')
);
この時点で、Tailwind CSSとreact-router-domを使用した新しいReactプロジェクトが作成されていることでしょう。
ステップ2 — AppReducer と GlobalContext の構築
最初に、srcディレクトリの下に新しいcontextディレクトリを作成します。
この新しいディレクトリに、新しい AppReducer.js ファイルを作成します。このリデューサーは、ADD_EMPLOYEE、EDIT_EMPLOYEE、および REMOVE_EMPLOYEE などのCRUDアクションを定義します。このファイルをコードエディタで開き、次のコード行を追加してください:
export default function appReducer(state, action) {
switch (action.type) {
case "ADD_EMPLOYEE":
return {
...state,
employees: [...state.employees, action.payload],
};
case "EDIT_EMPLOYEE":
const updatedEmployee = action.payload;
const updatedEmployees = state.employees.map((employee) => {
if (employee.id === updatedEmployee.id) {
return updatedEmployee;
}
return employee;
});
return {
...state,
employees: updatedEmployees,
};
case "REMOVE_EMPLOYEE":
return {
...state,
employees: state.employees.filter(
(employee) => employee.id !== action.payload
),
};
default:
return state;
}
};
ADD_EMPLOYEES は新しい従業員を含むペイロード値を受け取り、更新された従業員の状態を返します。
EDIT_EMPLOYEE はペイロード値を受け取り、id を従業員と比較します。一致するものが見つかれば、新しいペイロード値を使用して更新された従業員の状態を返します。
REMOVE_EMPLOYEEはペイロード値を取り、idを従業員と比較します - 一致するものが見つかれば、その従業員を削除し、更新された従業員の状態を返します。
「context」ディレクトリに残ったまま、新しい「GlobalState.js」ファイルを作成します。このファイルには、リクエストから返される従業員データを模倣するための初期のハードコーディングされた値が含まれます。このファイルをコードエディタで開き、次の行のコードを追加してください:
import React, { createContext, useReducer } from 'react';
import appReducer from './AppReducer';
const initialState = {
employees: [
{
id: 1,
name: "Sammy",
location: "DigitalOcean",
designation: "Shark"
}
]
};
export const GlobalContext = createContext(initialState);
export const GlobalProvider = ({ children }) => {
const [state, dispatch] = useReducer(appReducer, initialState);
function addEmployee(employee) {
dispatch({
type: "ADD_EMPLOYEE",
payload: employee
});
}
function editEmployee(employee) {
dispatch({
type: "EDIT_EMPLOYEE",
payload: employee
});
}
function removeEmployee(id) {
dispatch({
type: "REMOVE_EMPLOYEE",
payload: id
});
}
return (
<GlobalContext.Provider
value={{
employees: state.employees,
addEmployee,
editEmployee,
removeEmployee
}}
>
{children}
</GlobalContext.Provider>
);
};
このコードは、各アクションに対応するケースでスイッチするためにリデューサーファイルにアクションをディスパッチする機能を追加します。
この時点で、AppReducer.jsとGlobalState.jsを持つReactアプリケーションがあるはずです。
アプリケーションが正常に動作していることを確認するために、EmployeeList コンポーネントを作成しましょう。src ディレクトリに移動し、新しい components ディレクトリを作成します。そのディレクトリ内に新しい EmployeeList.js ファイルを作成し、以下のコードを追加します:
import React, { useContext } from 'react';
import { GlobalContext } from '../context/GlobalState';
export const EmployeeList = () => {
const { employees } = useContext(GlobalContext);
return (
<React.Fragment>
{employees.length > 0 ? (
<React.Fragment>
{employees.map((employee) => (
<div
className="flex items-center bg-gray-100 mb-10 shadow"
key={employee.id}
>
<div className="flex-auto text-left px-4 py-2 m-2">
<p className="text-gray-900 leading-none">
{employee.name}
</p>
<p className="text-gray-600">
{employee.designation}
</p>
<span className="inline-block text-sm font-semibold mt-1">
{employee.location}
</span>
</div>
</div>
))}
</React.Fragment>
) : (
<p className="text-center bg-gray-100 text-gray-500 py-5">No data.</p>
)}
</React.Fragment>
);
};
このコードは、すべてのemployeesに対してemployee.name、employee.designation、およびemployee.locationを表示します。
次に、コードエディタで App.js を開き、 EmployeeList と GlobalProvider を追加してください。
import { EmployeeList } from './components/EmployeeList';
import { GlobalProvider } from './context/GlobalState';
function App() {
return (
<GlobalProvider>
<div className="App">
<EmployeeList />
</div>
</GlobalProvider>
);
}
export default App;
アプリケーションを実行し、ウェブブラウザでそれを観察してください:
EmployeeListコンポーネントは、GlobalState.jsに設定されたハードコーディングされた値を表示します。
ステップ3 — AddEmployeeおよびEditEmployeeコンポーネントの構築
このステップでは、新しい従業員を作成し、既存の従業員を更新するためのコンポーネントを構築します。
さて、componentsディレクトリに戻ります。新しいAddEmployee.jsファイルを作成します。これはAddEmployeeコンポーネントとして機能し、フォームフィールドの値を状態にプッシュするためのonSubmitハンドラーを含みます:
import React, { useState, useContext } from 'react';
import { Link, useHistory } from 'react-router-dom';
import { GlobalContext } from '../context/GlobalState';
export const AddEmployee = () => {
let history = useHistory();
const { addEmployee, employees } = useContext(GlobalContext);
const [name, setName] = useState("");
const [location, setLocation] = useState("");
const [designation, setDesignation] = useState("");
const onSubmit = (e) => {
e.preventDefault();
const newEmployee = {
id: employees.length + 1,
name,
location,
designation,
};
addEmployee(newEmployee);
history.push("/");
};
return (
<React.Fragment>
<div className="w-full max-w-sm container mt-20 mx-auto">
<form onSubmit={onSubmit}>
<div className="w-full mb-5">
<label
className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
htmlFor="name"
>
Name of employee
</label>
<input
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:text-gray-600"
value={name}
onChange={(e) => setName(e.target.value)}
type="text"
placeholder="Enter name"
/>
</div>
<div className="w-full mb-5">
<label
className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
htmlFor="location"
>
Location
</label>
<input
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:text-gray-600 focus:shadow-outline"
value={location}
onChange={(e) => setLocation(e.target.value)}
type="text"
placeholder="Enter location"
/>
</div>
<div className="w-full mb-5">
<label
className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
htmlFor="designation"
>
Designation
</label>
<input
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:text-gray-600"
value={designation}
onChange={(e) => setDesignation(e.target.value)}
type="text"
placeholder="Enter designation"
/>
</div>
<div className="flex items-center justify-between">
<button className="mt-5 bg-green-400 w-full hover:bg-green-500 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline">
Add Employee
</button>
</div>
<div className="text-center mt-4 text-gray-500">
<Link to="/">Cancel</Link>
</div>
</form>
</div>
</React.Fragment>
);
};
このコードでは、setName、setLocation、およびsetDesignationが、ユーザーがフォームフィールドに入力した現在の値を取得します。これらの値は、新しい定数newEmployeeにラップされ、一意のid(合計の長さに1を加えたもの)が付与されます。次に、ルートがメイン画面に変更され、更新された従業員のリストが表示されます - 追加されたばかりの従業員を含む。
AddEmployee コンポーネントは GlobalState と、組み込みの React フックの一つである useContext をインポートし、関数コンポーネントがコンテキストに簡単にアクセスできるようにしました。
employeesオブジェクト、removeEmployee、およびeditEmployeesは、GlobalState.jsファイルからインポートされました。
まだcomponentsディレクトリにいる間に、新しいEditEmployee.jsファイルを作成します。これは、状態から既存のオブジェクトを編集する機能を含むeditEmployeeコンポーネントとして機能します。
import React, { useState, useContext, useEffect } from 'react';
import { useHistory, Link } from 'react-router-dom';
import { GlobalContext } from '../context/GlobalState';
export const EditEmployee = (route) => {
let history = useHistory();
const { employees, editEmployee } = useContext(GlobalContext);
const [selectedUser, setSelectedUser] = useState({
id: null,
name: "",
designation: "",
location: "",
});
const currentUserId = route.match.params.id;
useEffect(() => {
const employeeId = currentUserId;
const selectedUser = employees.find(
(currentEmployeeTraversal) => currentEmployeeTraversal.id === parseInt(employeeId)
);
setSelectedUser(selectedUser);
}, [currentUserId, employees]);
const onSubmit = (e) => {
e.preventDefault();
editEmployee(selectedUser);
history.push("/");
};
const handleOnChange = (userKey, newValue) =>
setSelectedUser({ ...selectedUser, [userKey]: newValue });
if (!selectedUser || !selectedUser.id) {
return <div>Invalid Employee ID.</div>;
}
return (
<React.Fragment>
<div className="w-full max-w-sm container mt-20 mx-auto">
<form onSubmit={onSubmit}>
<div className="w-full mb-5">
<label
className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
htmlFor="name"
>
Name of employee
</label>
<input
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:text-gray-600 focus:shadow-outline"
value={selectedUser.name}
onChange={(e) => handleOnChange("name", e.target.value)}
type="text"
placeholder="Enter name"
/>
</div>
<div className="w-full mb-5">
<label
className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
htmlFor="location"
>
Location
</label>
<input
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:text-gray-600 focus:shadow-outline"
value={selectedUser.location}
onChange={(e) => handleOnChange("location", e.target.value)}
type="text"
placeholder="Enter location"
/>
</div>
<div className="w-full mb-5">
<label
className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
htmlFor="designation"
>
Designation
</label>
<input
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:text-gray-600 focus:shadow-outline"
value={selectedUser.designation}
onChange={(e) => handleOnChange("designation", e.target.value)}
type="text"
placeholder="Enter designation"
/>
</div>
<div className="flex items-center justify-between">
<button className="block mt-5 bg-green-400 w-full hover:bg-green-500 text-white font-bold py-2 px-4 rounded focus:text-gray-600 focus:shadow-outline">
Edit Employee
</button>
</div>
<div className="text-center mt-4 text-gray-500">
<Link to="/">Cancel</Link>
</div>
</form>
</div>
</React.Fragment>
);
};
このコードは、コンポーネントがマウントされると呼び出される useEffect フックを使用しています。このフック内で、現在のルートパラメーターが状態の employees オブジェクト内の同じパラメーターと比較されます。
onChangeイベントリスナーは、ユーザーがフォームフィールドを変更したときにトリガーされます。userKeyとnewValueがsetSelectedUserに渡されます。selectedUserはスプレッドされ、userKeyがキーとして設定され、newValueが値として設定されます。
ステップ4 — ルートの設定
このステップでは、EmployeeListを更新して、AddEmployeeおよびEditEmployeeコンポーネントにリンクします。
EmployeeList.jsを再訪し、LinkとremoveEmployeeを使用するように修正してください。
import React, { useContext } from 'react';
import { Link } from 'react-router-dom';
import { GlobalContext } from '../context/GlobalState';
export const EmployeeList = () => {
const { employees, removeEmployee } = useContext(GlobalContext);
return (
<React.Fragment>
{employees.length > 0 ? (
<React.Fragment>
{employees.map((employee) => (
<div
className="flex items-center bg-gray-100 mb-10 shadow"
key={employee.id}
>
<div className="flex-auto text-left px-4 py-2 m-2">
<p className="text-gray-900 leading-none">
{employee.name}
</p>
<p className="text-gray-600">
{employee.designation}
</p>
<span className="inline-block text-sm font-semibold mt-1">
{employee.location}
</span>
</div>
<div className="flex-auto text-right px-4 py-2 m-2">
<Link
to={`/edit/${employee.id}`}
title="Edit Employee"
>
<div className="bg-gray-300 hover:bg-gray-400 text-gray-800 font-semibold mr-3 py-2 px-4 rounded-full inline-flex items-center">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="feather feather-edit"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>
</div>
</Link>
<button
onClick={() => removeEmployee(employee.id)}
className="block bg-gray-300 hover:bg-gray-400 text-gray-800 font-semibold py-2 px-4 rounded-full inline-flex items-center"
title="Remove Employee"
>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="feather feather-trash-2"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg>
</button>
</div>
</div>
))}
</React.Fragment>
) : (
<p className="text-center bg-gray-100 text-gray-500 py-5">No data.</p>
)}
</React.Fragment>
);
};
このコードは、従業員情報の隣に2つのアイコンを追加します。鉛筆と紙のアイコンは「編集」を表し、EditEmployeeコンポーネントにリンクしています。ゴミ箱のアイコンは「削除」を表し、クリックするとremoveEmployeeが実行されます。
次に、EmployeeListコンポーネントを表示し、ユーザーがAddEmployeeコンポーネントにアクセスできるようにするために、2つの新しいコンポーネント - HeadingとHome - を作成します。
componentsディレクトリに新しいHeading.jsファイルを作成します。
import React from "react";
import { Link } from "react-router-dom";
export const Heading = () => {
return (
<div>
<div className="flex items-center mt-24 mb-10">
<div className="flex-grow text-left px-4 py-2 m-2">
<h5 className="text-gray-900 font-bold text-xl">Employee Listing</h5>
</div>
<div className="flex-grow text-right px-4 py-2 m-2">
<Link to="/add">
<button className="bg-green-400 hover:bg-green-500 text-white font-semibold py-2 px-4 rounded inline-flex items-center">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="feather feather-plus-circle"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="16"></line><line x1="8" y1="12" x2="16" y2="12"></line></svg>
<span className="pl-2">Add Employee</span>
</button>
</Link>
</div>
</div>
</div>
);
};
componentsディレクトリに新しいHome.jsファイルを作成します。
import React from "react";
import { Heading } from "./Heading";
import { EmployeeList } from "./EmployeeList";
export const Home = () => {
return (
<React.Fragment>
<div className="container mx-auto">
<h3 className="text-center text-3xl mt-20 text-base leading-8 text-black font-bold tracking-wide uppercase">
CRUD with React Context API and Hooks
</h3>
<Heading />
<EmployeeList />
</div>
</React.Fragment>
);
};
App.jsを再訪し、react-router-domからRouteとSwitchをインポートします。Home、AddEmployee、EditEmployeeコンポーネントをそれぞれのルートに割り当てます:
import { Route, Switch } from 'react-router-dom';
import { GlobalProvider } from './context/GlobalState';
import { Home } from './components/Home';
import { AddEmployee } from './components/AddEmployee';
import { EditEmployee } from './components/EditEmployee';
function App() {
return (
<GlobalProvider>
<div className="App">
<Switch>
<Route path="/" component={Home} exact />
<Route path="/add" component={AddEmployee} exact />
<Route path="/edit/:id" component={EditEmployee} exact />
</Switch>
</div>
</GlobalProvider>
);
}
export default App;
アプリをコンパイルして、ブラウザで観察します。
あなたはHeadingとEmployeeListコンポーネントを持つHomeコンポーネントにルーティングされます:
従業員を追加リンクをクリックしてください。AddEmployeeコンポーネントに移動します:
新しい従業員の情報を提出した後、あなたはHomeコンポーネントに戻され、そこに新しい従業員がリストされます。
従業員を編集リンクをクリックしてください。EditEmployeeコンポーネントに移動します:
従業員の情報を変更した後、あなたはHomeコンポーネントに戻され、更新された詳細を持つ新しい従業員のリストが表示されます。
結論
この記事では、Context APIとReactフックを組み合わせて、完全に機能するCRUDアプリケーションを構築しました。
Reactについてもっと学びたい方は、私たちの「React.jsでのコーディング方法」シリーズを見ていただくか、演習やプログラミングプロジェクトのためのReactトピックページをご覧ください。




