📝

Amplify Studio のカスタムコンポーネントを React に組み込んでみた

に公開

Amplify Studio のチュートリアルレベルの内容です。

前提

  • AdministratorAccess 権限が付与された IAM ユーザーを作成済み
  • IAM ユーザーの認証情報を発行済み

01. Amplify アプリの作成

「Gen 1 でアプリを作成」をクリックします。

「アプリケーションの名前」を入力してデプロイします。

デプロイ完了後、Amplify Studio を起動します。

02. コンポーネントの作成

左ペインの Design > UI LIbrary をクリックし、Forms の「New」をクリックします。

Form name を入力してフォームを作成します。

「+」マークをクリックして「JSONField」を選択します。

Label などを設定します。

  • Labal: 設定データ
  • Placeholder: {"theme": "dark", "language": "ja"}
  • Descriptive text: アプリケーションの設定をJSON形式で入力してください

03. React プロジェクト作成

今回は Cloud9 で作成しました。

$ npx create-react-app amplify-studio-test
$ cd amplify-studio-test

# Amplify CLI のインストール
$ mkdir -p ~/.npm-global
$ npm config set prefix '~/.npm-global'
$ echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
$ source ~/.bashrc
$ npm install -g @aws-amplify/cli

# Amplify CLI の設定
$ amplify configure

# IAM ユーザーの認証情報をセット
Enter the access key of the newly created user:
? accessKeyId:  ********************
? secretAccessKey:  ****************************************

04. Amplify プロジェクトを pull

プルコマンドは以下の画面から確認できます。

$ npm install "@aws-amplify/ui-react@^6.0.0"
$ npm install "aws-amplify@^6.0.0"

$ amplify pull --appId d3mi452wkh03gi --envName staging
...
Do you plan on modifying this backend? (Y/n) n

05. React アプリにコンポーネントを組み込む

src/App.js
import React from 'react';
import './App.css';
import { CustomComponent1 } from './ui-components';
import { ThemeProvider } from '@aws-amplify/ui-react';
import studioTheme from './ui-components/studioTheme';
import '@aws-amplify/ui-react/styles.css';

function App() {
  const handleFormSubmit = (fields) => {
    console.log('フォームが送信されました:', fields);
    alert('設定データ: ' + JSON.stringify(fields, null, 2));
  };

  return (
    <ThemeProvider theme={studioTheme}>
      <div className="App">
        <header className="App-header">
          <h1>🚀 Amplify Studio コンポーネントテスト</h1>
          <p>Amplify Studioで作成したカスタムコンポーネントです</p>
          
          <CustomComponent1 
            onSubmit={handleFormSubmit}
          />
        </header>
      </div>
    </ThemeProvider>
  );
}

export default App;
$ npm start

プレビュー画面で以下のページが表示されれば OK です。

テストデータを送信するとアラートが表示されます。

まとめ

今回は Amplify Studio のカスタムコンポーネントを React に組み込んでみました。
どなたかの参考になれば幸いです。

Discussion