0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ChatGPTを使用したアプリ開発記【翻訳ボタンの実装】

Posted at

1. props

TranslateButton.js
export const TranslateButton = ({ text, targetLang = 'en' }) => {

• text: 翻訳したいテキスト(親コンポーネントから渡される)。
• targetLang: 翻訳後の言語(デフォルトは 'en' = 英語)。

2. useState の定義

TranslateButton.js
const [translated, setTranslated] = useState(null);
const [loading, setLoading] = useState(false);

• translated: 翻訳結果を保存するステート。
• loading: 翻訳中かどうかを表すステート(ボタンを無効化するために使う)。

3. 翻訳処理の実行関数

TranslateButton.js
const translateText = async () => {
  if (!text.trim()) return;

• 空文字列を防止。

TranslateButton.js
setLoading(true);
try {
  const res = await fetch('http://localhost:5001/translate', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      q: text,
      source: 'auto',
      target: targetLang,
      format: 'text'
    }),
  });

  const json = await res.json();
  if (!res.ok) throw new Error(json.error || res.statusText);

  setTranslated(json.translatedText);
} catch (e) {
  console.error("翻訳エラー:", e);
  alert(`翻訳に失敗しました: ${e.message}`);
} finally {
  setLoading(false);
}

• API に翻訳リクエストを送る(POST リクエスト)。
• 結果が json.translatedText にあると仮定し、それを translated に保存。
• エラー時はアラートを表示。

4. JSX による UI 表示

TranslateButton.js
<button
  type="button"
  onClick={(e) => {
    e.stopPropagation(); // ← 親要素のクリックイベントを妨げる
    translateText();     // 翻訳処理を呼び出す
  }}
  disabled={loading}
  className="..."
>
  {loading ? '翻訳中...' : '翻訳する'}
</button>

• ボタンクリック時に翻訳実行。
• 翻訳中は「翻訳中…」と表示、ボタンは無効化。

5. 翻訳結果の表示

TranslateButton.js
{translated && (
  <div className="...">
    <p className="text-sm text-gray-700">翻訳結果:</p>
    <p className="text-base">{translated}</p>
  </div>
)}

• 翻訳結果が存在する場合のみ表示。

✅ このコンポーネントを使うには?

TranslateButton.js
<TranslateButton text="こんにちは世界" targetLang="en" />

このように使えば、「こんにちは世界」が英語に翻訳され、結果が表示されます。

UI

スクリーンショット 2025-06-10 21.07.35.png

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?