2️⃣

【Laravel10】 Inertia + React で「追加・変更・削除・閲覧」機能をつくる(その2)

2024/07/23に公開

概要

【Laravel10】 Inertia + React で「追加・変更・削除・閲覧」機能をつくる(その1)の続編です。
前回は、indexアクションのみ実装完了していたので、今回はnewアクションを実装します。

バージョン情報

その1から同じなので、割愛

PostController::newを実装

コントローラ側

app/Http/Controllers/PostController.phpを編集

app/Http/Controllers/PostController.php
<?php

namespace App\Http\Controllers;

use App\UseCases\Post\IndexAction;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class PostController extends Controller
{
    public function index(IndexAction $action): Response
    {
        return Inertia::render('Post/Index', $action());
    }

    public function new(): Resopnse
    {
        return Inertia::render('Post/Create');
    }

    public function store()
    {
    }

    public function show()
    {
    }

    public function edit()
    {
    }

    public function update()
    {
    }

    public function destroy()
    {
    }
}

コンポーネント側

resources/js/Pages/Post/Create.jsxを編集

mkdir resources/js/Pages/Post 
touch resources/js/Pages/Post/Create.jsx
resources/js/Pages/Post/Create.jsx
import React from 'react';
import PostForm from "@/Components/Post/Form";

export default function Create(props) {

    const { post, errors } = props;

    return (
        <PostForm type="create" post={post} errors={errors}></PostForm>
    );

}

resources/js/Components/Post/Form.jsxを作成

と、その前に、lodashを入れてください。必須ではないけど、あると便利な関数が色々使用できます。
npm install --save-dev lodash

mkdir resources/js/Components/Post
touch resources/js/Components/Post/Form.jsx
resources/js/Components/Post/Form.jsx
import React, { useState } from 'react';
import { Link, useForm } from '@inertiajs/react';
import Loading from "@/Components/Loading";
import _ from 'lodash';


export default function Form(props) {

    // Data
    const type = props.type; // create or edit
    const row = props.post;
    const errors = props.errors;
    const { data, setData, processing, post } = useForm({
        title: _.get(row, 'title', ''),
        body: _.get(row, 'body', ''),
    });
    const [loading, setLoading] = useState(false);

    // Methods
    const onFinish = () => setLoading(false);
    const onSubmit = () => {

        setLoading(true);

        if(type === 'create') { // 登録 or 変更で切り替える

            const url = route('posts.input.store');
            post(url, { onFinish });

        } else if(type === 'edit') {

            const url = route('posts.input.update', props.post.id);
            put(url, { onFinish });

        }

    };

    return (
        <div className="p-4">
            <div className="mb-3">
            <label htmlFor="title" className='text-sm block'>タイトル</label>
                <input id="title" className="w-80 border border-gray-500 p-2 rounded" value={data.title} onChange={e => setData('title', e.target.value)} />
                {errors.title && <div className="mt-2 text-red-500 bg-red-100 p-2 rounded">{errors.title}</div>}
            </div>
            <div className="mb-3">
                <label htmlFor="body" className="text-sm block">本文</label>
                <textarea id="body" className="w-80 border border-gray-500 p-2 rounded" value={data.body} onChange={e => setData('body', e.target.value)} />
                {errors.body && <div className="mt-2 text-red-500 bg-red-100 p-2 rounded">{errors.body}</div>}
            </div>
            <button type="button" className="text-white bg-blue-700 rounded-lg text-sm px-4 py-2 mr-5" onClick={onSubmit} disabled={processing}>送信する</button>
            <Link href={route('posts.view.index')}>戻る</Link>
            <br />
            <Loading show={loading}></Loading>
        </div>
    );

}

resources/js/Components/Loading.jsxを作成

resources/js/Components/Loading.jsx
import React from 'react';

export default function Loading({ show = false }) {

    return (
        <>
            {show && <span>読み込み中...</span>}
        </>
    );

}

確認

npm run dev をして、http://localhost/posts にアクセスして、「追加する」をクリックしてみてください。
http://localhost/posts/new に遷移して、フォームが表示されることが確認できます。

ビューだけなので、まだDBの登録はできません。

【Laravel10】 Inertia + React で「追加・変更・削除・閲覧」機能をつくる(その3)に続きます。

関連記事

Discussion