2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React + Firebase Authenticationでログイン機能を簡単に実装する

Last updated at Posted at 2021-02-28

##はじめに

FirebaseのAuthenticationを使って、超簡単にReactアプリケーションのログイン(認証)機能を実装します。
いくつか既に記事はあるかと思いますが、ちょっと古かったり、動かなかったりしたので、記事に残してきます。
ご参考になれば幸いです!

前提

  • npx create-react-app等でReactプロジェクトの作成が完了していること
  • Firebaseコンソール上でのプロジェクト作成、登録が完了していること

Firebase上での作業がまだの方は、下記などを参考に進めてください。
https://yanou.jp/react-firebase-authentication/

ざっくり流れ

  1. Firebase SDKをReactアプリケーションで読み込む
  2. ユーザー登録、ログイン機能を実装する

なお、記事が長くならないように、
※CSSは書いておりません
※ユーザー登録とログインボタンが同一コンポーネント内にありますがご容赦ください...

それでは詳細を見ていきましょう。

##手順①Firebase SDKをReactアプリケーションで読み込む

SDKの場所は、下記の設定マーク→プロジェクトを設定→ページ下部にあります。
スクリーンショット 2021-02-28 18.58.55.png

1. firebaseをインストール

npm i firebase

2. src配下にfirebaseファイルを作成する

firebaseConfig.ts
import firebase from 'firebase/app'
import 'firebase/auth'

const firebaseConfig = {
  apiKey: "hogehoge",
  authDomain: "hoge.firebaseapp.com",
  projectId: "hoge",
  storageBucket: "hoge.com",
  messagingSenderId: "hoge",
  appId: "hogehogehoge"
}

const fire = firebase.initializeApp(firebaseConfig)

export default fire

手順②ユーザー登録、ログイン機能を実装する

import React, { useState } from "react";
// firebaseConfigからfireをインポートする
import fire from "./firebaseConfig";

export const App: React.FC = () => {
  //ユーザー管理用state
  const [user, setUser] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  //ログインメソッド
  const handleLogin = () => {
    fire
      .auth()
      .signInWithEmailAndPassword(email, password)
  };

  //ユーザー登録メソッド
  const handleSignup = () => {
    fire
      .auth()
      .createUserWithEmailAndPassword(email, password)
  };
  
  //ログインしているかをチェックするメソッド
  const isLogin = () => {
    fire.auth().onAuthStateChanged((user) => {
      if (user) {
        setUser(user);
      } else {
        setUser("");
      }
    });
  };
  
  //レンダー後にisLoginを実行する
  useEffect(() => {
    isLogin();
  }, []);

  return (
    <div>
      {/* userのstateでコンポーネントを切り替えている */}
      { user ? (
         {/* ログイン後に表示したいコンポーネントを書く */}
      ) : (
        <div>
          <label htmlFor="email">メールアドレス</label>
          <input
            id="email"
            type="text"
            placeholder="メールアドレス"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </div>
        <div>
          <label htmlFor="password">パスワード</label>
          <input
            id="password"
            type="password"
            placeholder="パスワード"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
        </div>
        <div>
          <button
            type="button"
            onClick={handleSignup}
          >
            ユーザー登録する
          </button>
          <button
            type="button"
            onClick={handleLogin}
          >
            ログインする
          </button>
      </div>
      )}
    </div>
  );
};

これで完了です🙌

終わりに

これだけの記述で認証機能が実装できるのは本当に楽ですね。
長い記事にしたくなかったので、コードの詳細は端折っております。何か質問があれば、コメントください!

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?