programing

reactjs를 사용하여 Facebook API 로그인 구현

showcode 2023. 3. 21. 22:42
반응형

reactjs를 사용하여 Facebook API 로그인 구현

Facebook의 Javascript SDK를 인증에 사용하고 있습니다.SDK를 올바르게 Import 할 수 있게 되어, 페이지에 「좋아요」버튼을 붙일 수 있게 되었습니다.단, Facebook 로그인 버튼은 태그로 감싸야 합니다.

<fb:login-button/>

현재 Facebook 로그인 튜토리얼의 모든 코드를 내 프로젝트의 유일한 html 파일인 index.html에 붙여넣고 있습니다.이 파일은 리액트 어플리케이션을 포함하고 있습니다.그러나 실제 로그인 버튼이 있는 마지막 부분을 React 컴포넌트에 넣어야 합니다.이것을 하려고 했을 때, 다음의 에러가 발생했습니다.

ReactifyError: /Users/ritmatter/reps/js/components/Signup.jsx: Parse Error: Line 82: Unexpected end of input while parsing file: /Users/ritmatter/reps/js/components/Signup.jsx
sdk.js:61 The "fb-root" div has not been created, auto-creating
ping?client_id=894010190618709&domain=localhost&origin=1&redirect_uri=http%3A%2F%2Fstatic.ak.facebo…:1 Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings.  It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.

로그인 버튼을 반응시키려면 어떻게 해야 하나요?

ReactJs 로그인 API 페이스북 튜토리얼을 수정하는 방법을 알아냈습니다.

먼저 Login 링크를 사용하는 리액트컴포넌트에 다음 코드를 포함합니다.

componentDidMount: function() {
  window.fbAsyncInit = function() {
    FB.init({
      appId      : '<YOUR_APP_ID>',
      cookie     : true,  // enable cookies to allow the server to access
                        // the session
      xfbml      : true,  // parse social plugins on this page
      version    : 'v2.1' // use version 2.1
    });

    // Now that we've initialized the JavaScript SDK, we call
    // FB.getLoginStatus().  This function gets the state of the
    // person visiting this page and can return one of three states to
    // the callback you provide.  They can be:
    //
    // 1. Logged into your app ('connected')
    // 2. Logged into Facebook, but not your app ('not_authorized')
    // 3. Not logged into Facebook and can't tell if they are logged into
    //    your app or not.
    //
    // These three cases are handled in the callback function.
    FB.getLoginStatus(function(response) {
      this.statusChangeCallback(response);
    }.bind(this));
  }.bind(this);

  // Load the SDK asynchronously
  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
},

// Here we run a very simple test of the Graph API after login is
// successful.  See statusChangeCallback() for when this call is made.
testAPI: function() {
  console.log('Welcome!  Fetching your information.... ');
  FB.api('/me', function(response) {
  console.log('Successful login for: ' + response.name);
  document.getElementById('status').innerHTML =
    'Thanks for logging in, ' + response.name + '!';
  });
},

// This is called with the results from from FB.getLoginStatus().
statusChangeCallback: function(response) {
  console.log('statusChangeCallback');
  console.log(response);
  // The response object is returned with a status field that lets the
  // app know the current login status of the person.
  // Full docs on the response object can be found in the documentation
  // for FB.getLoginStatus().
  if (response.status === 'connected') {
    // Logged into your app and Facebook.
    this.testAPI();
  } else if (response.status === 'not_authorized') {
    // The person is logged into Facebook, but not your app.
    document.getElementById('status').innerHTML = 'Please log ' +
      'into this app.';
  } else {
    // The person is not logged into Facebook, so we're not sure if
    // they are logged into this app or not.
    document.getElementById('status').innerHTML = 'Please log ' +
    'into Facebook.';
  }
},

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
checkLoginState: function() {
  FB.getLoginStatus(function(response) {
    this.statusChangeCallback(response);
  }.bind(this));
},

handleClick: function() {
  FB.login(this.checkLoginState());
},

그런 다음 렌더링 메서드에서 handle을 호출할 HTML이 있는지 확인합니다.클릭:

<a href="#" onClick={this.handleClick}>Login</a>

이 코드는 튜토리얼과 동일하지만 리액트에 배치되어 있습니다.JS 컴포넌트유일한 차이점은 Facebook API 기능을 반응 컴포넌트의 일부로 만들기 위해 이 기능을 전략적으로 바인드해야 한다는 것입니다.이 로그인은 FB.getLoginStatus()에 의해 주어진 응답에서 해석된 응답 메시지로 종료됩니다.또한 이 응답 객체에서 토큰을 꺼내 passport-facebook-token 등의 인증을 위해 백엔드로 전송할 수도 있습니다.

Facebook Auth 흐름에 Promise를 사용했습니다.

믹스인 / 믹스인 / 믹스인js

const promises = {
    init: () => {
        return new Promise((resolve, reject) => {
            if (typeof FB !== 'undefined') {
                resolve();
            } else {
                window.fbAsyncInit = () => {
                    FB.init({
                        appId      : '<app_id>',
                        cookie     : true, 
                        xfbml      : true,  
                        version    : 'v2.5'
                    });
                    resolve();
                };
                (function(d, s, id) {
                    var js, fjs = d.getElementsByTagName(s)[0];
                    if (d.getElementById(id)) return;
                    js = d.createElement(s); js.id = id;
                    js.src = "//connect.facebook.net/en_US/sdk.js";
                    fjs.parentNode.insertBefore(js, fjs);
                }(document, 'script', 'facebook-jssdk'));
            }
        });
    },
    checkLoginState: () => {
        return new Promise((resolve, reject) => {
            FB.getLoginStatus((response) => {
                response.status === 'connected' ? resolve(response) : reject(response);
            });
        });
    },
    login: () => {
        return new Promise((resolve, reject) => {
            FB.login((response) => {
                response.status === 'connected' ? resolve(response) : reject(response);
            });
        });
    },
    logout: () => {
        return new Promise((resolve, reject) => {
            FB.logout((response) => {
                response.authResponse ? resolve(response) : reject(response);
            });
        });
    },
    fetch: () => {
        return new Promise((resolve, reject) => {
            FB.api(
                '/me', 
                {fields: 'first_name, last_name, gender'},
                response => response.error ? reject(response) : resolve(response)
            );
        });
    }
}

export const Facebook = {
    doLogin() {
        this.setState({
            loading: true
        }, () => {
            promises.init()
                .then(
                    promises.checkLoginState,
                    error => { throw error; }
                )
                .then(
                    response => { this.setState({status: response.status}); },
                    promises.login
                )
                .then(
                    promises.fetch,
                    error => { throw error; }
                )
                .then(
                    response => { this.setState({loading: false, data: response, status: 'connected'}); },
                    error => { throw error; }
                )
                .catch((error) => { 
                    this.setState({loading: false, data: {}, status: 'unknown'});
                    console.warn(error); 
                });
        });
    },
    doLogout() {
        this.setState({
            loading: true
        }, () => {
            promises.init()
                .then(
                    promises.checkLoginState,
                    error => { throw error; }
                )
                .then(
                    promises.logout,
                    error => { this.setState({data: {}, status: 'unknown'}); }
                )
                .then(
                    response => { this.setState({loading: false, data: {}, status: 'unknown'}); },
                    error => { throw error; }
                )
                .catch(error => { 
                    this.setState({loading: false, data: {}, status: 'unknown'});
                    console.warn(error); 
                });
        });
    },
    checkStatus() {
        this.setState({
            loading: true
        }, () => {
            promises.init()
                .then(
                    promises.checkLoginState,
                    error => { throw error; }
                )
                .then(
                    response => { this.setState({status: response.status}); },
                    error => { throw error; }
                )
                .then(
                    promises.fetchUser,
                    error => { throw error; }
                )
                .then(
                    response => { this.setState({loading: false, data: response, status: 'connected'}); },
                    error => { throw error; }
                )
                .catch((error) => { 
                    this.setState({loading: false, data: {}, status: 'unknown'});
                    console.warn(error); 
                });
        });
    }
};

Profile.jsx

import {Facebook} from './mixins/Facebook.js';
import {Button} from 'react-bootstrap';

const ProfileHandler = React.createClass({
    mixins: [Facebook],
    componentDidMount() {
        this.checkStatus();
    },
    getInitialState() {
        return {
            status: 'unknown',
            loading: false,
            data: {}
        };
    },
    render() {
        const loading = this.state.loading ? <p>Please wait, profile is loading ...</p> : null;
        const message = this.state.status === 'connected'
            ? (<div>
                Hi {data.name}!
                <Button onClick={this.doLogout}>Logout</Button>
              </div>)
            : (<Button onClick={this.doLogin}>Login</Button>);
        return (
            <div>
                {message}
                {loading}
            </div>
        );
    }
});

릿매터가 좋은 대답을 해줬는데 어떻게 다르게 했는지 보여드릴게요.로그인 상태를 확인하기 위한 콜백을 트리거하기 위해 내 것이 아닌 페이스북의 로그인 버튼을 사용하고 싶었다.로그인 버튼은 다음과 같습니다.

<div class="fb-login-button" onlogin="checkLoginState" data-size="medium" data-show-faces="false" data-auto-logout-link="false"></div>

버튼에는 jsx 파서가 지원하지 않는 onlogin 속성이 있습니다.리액트 방식으로 데이터 온로그인을 사용할 수 없었기 때문에 componentDidMount에 버튼을 추가했을 뿐입니다.

        componentWillMount: function () {
                window['statusChangeCallback'] = this.statusChangeCallback;
                window['checkLoginState'] = this.checkLoginState;
        },
        componentDidMount: function () {
            var s = '<div class="fb-login-button" ' +
                'data-scope="public_profile,email" data-size="large" ' +
                'data-show-faces="false" data-auto-logout-link="true" ' +
                'onlogin="checkLoginState"></div>';

            var div = document.getElementById('social-login-button-facebook')
            div.innerHTML = s;
        },
        componentWillUnmount: function () {
            delete window['statusChangeCallback'];
            delete window['checkLoginState'];
        },
        statusChangeCallback: function(response) {
           console.log(response);
        },
        // Callback for Facebook login button
        checkLoginState: function() {
            console.log('checking login state...');
            FB.getLoginStatus(function(response) {
               statusChangeCallback(response);
            });
        },
        render: function() {

            return (
                <div id='social-login-button-facebook'>

                </div>
            );
        }

이제 checkLoginState를 자동으로 호출하려면 컴포넌트 마운트 시 버튼을 트리거하기만 하면 됩니다.

답변이 구현에 도움이 되었기 때문에 여기에 내 해결책을 게시합니다. 그러나 리터로부터 받아들여진 답변은 이 솔루션 없이는 작동하지 않았습니다.

FB.Event.subscribe('auth.statusChange', function(response)

RubyFanatic의 답변에서 나온 진술입니다.게다가 "온로그인"은 나를 매우 혼란스럽게 했다.그것은 내 눈에는 전혀 필요하지 않다.

이것은 c&p 솔루션이기 때문에 fb api v2.8에 대한 완전한 코드(물론 react-bootstrap은 기동할 수 있습니다)를 공유하고 싶습니다.

/* global FB*/
import React, { Component } from 'react';
import { Grid, Row, Col } from 'react-bootstrap';

export default class Login extends Component {
  constructor(props) {
    super(props);
    this.checkLoginState = this.checkLoginState.bind(this);
    this.handleClick = this.handleClick.bind(this);
    this.testAPI = this.testAPI.bind(this);
    this.statusChangeCallback = this.statusChangeCallback.bind(this);
  }

  componentDidMount() {
    window.fbAsyncInit = function() {
      FB.init({
        appId      : 'YOURAPIKEYHERE',
        cookie     : true,
        xfbml      : true,
        version    : 'v2.8'
      });
      FB.AppEvents.logPageView();
      FB.Event.subscribe('auth.statusChange', function(response) {
        if (response.authResponse) {
          this.checkLoginState();
        } else {
          console.log('---->User cancelled login or did not fully authorize.');
        }
      }.bind(this));
    }.bind(this);

    // Load the SDK asynchronously
    (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = '//connect.facebook.net/en_US/sdk.js';
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
  }

  // Here we run a very simple test of the Graph API after login is
  // successful.  See statusChangeCallback() for when this call is made.
  testAPI() {
    console.log('Welcome! Fetching your information.... ');
    FB.api('/me', function(response) {
      console.log('Successful login for: ' + response.name);
      document.getElementById('status').innerHTML =
        'Thanks for logging in, ' + response.name + '!';
    });
  }

  // This is called with the results from from FB.getLoginStatus().
  statusChangeCallback(response) {
    if (response.status === 'connected') {
      // Logged into your app and Facebook.
      this.testAPI();
    } else if (response.status === 'not_authorized') {
      // The person is logged into Facebook, but not your app.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into this app.';
    } else {
      // The person is not logged into Facebook, so we're not sure if
      // they are logged into this app or not.
      document.getElementById('status').innerHTML = 'Please log ' +
      'into Facebook.';
    }
  }

  checkLoginState() {
    FB.getLoginStatus(function(response) {
      this.statusChangeCallback(response);
    }.bind(this));
  }

  handleClick() {
    FB.login(this.checkLoginState());
  }

  render() {
    return (
      <main>
        <Grid fluid>
            <h1>
              Facebook Login
            </h1>
        </Grid>
        <Grid>
          <Row>
            <Col xs={12}>
              <a href="#" onClick={this.handleClick} onlogin={this.checkLoginState}>Login</a>
              <div id="status"></div>
            </Col>
          </Row>
        </Grid>
      </main>
    );
  }
}

이것이 로그인 콜백을 받기 위해 사용한 솔루션입니다.렌더링 방법에서 Facebook 로그인 버튼에 다음 코드를 추가할 수 있습니다.

<div className="fb-login-button" data-max-row="5" 
     data-size="large" 
     data-show-faces="false" 
     data-auto-logout-link="false" 
     href="javascript:void(0)">Login</div>

코드에 다음 행을 추가합니다.

componentDidMount: function() {
    // facebook signin  button render
    window.fbAsyncInit = function() {
      FB.init({
        appId      : 'replace with your app id here',
        cookie     : true,  // enable cookies to allow the server to access
        // the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.1' // use version 2.1
      });

      // login callback implementation goes inside the function() { ... } block
      FB.Event.subscribe('auth.statusChange', function(response) {
        // example implementation
        if (response.authResponse) {
          console.log('Welcome!  Fetching your information.... ');
          FB.api('/me', function(response) {
            console.log('Good to see you, ' + response.name + '.');
          });
        } else {
          console.log('User cancelled login or did not fully authorize.');
        }
      });
    }.bind(this);

    // Load the SDK asynchronously
    (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
  }
}

FB에게 전화한다.컴포넌트 초기화 중 Event.subscribe('auth.statusChange', callback_function)는 기본적으로 로그인 콜백이기 때문에 중요합니다.FB는 이쪽에서 계산해 주세요.이벤트 문서

저는 최근에 제 프로젝트 중 하나를 위해 페이스북 로그인을 하고 있었습니다. 그래서 Stackoverflow의 답변과 블로그 투고를 많이 살펴본 결과입니다.ES6 FatArrow 함수식(.bind(this) 제외)을 사용하여 최소 탄성 코드를 작성했습니다.이 코드가 도움이 되길 바랍니다.

https://gist.github.com/ronit-mukherjee/3e933509643a4ab4e80452bb05c1a073

/*global FB*/
import React, {
  Component
} from 'react';

class FacebookLoginButton extends Component {
  componentDidMount() {
    (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {
        return;
      }
      js = d.createElement(s);
      js.id = id;
      js.src = "https://connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));


    window.fbAsyncInit = () => {
      FB.init({
        appId: '9999999999999999', //Change with your Facebook app id
        autoLogAppEvents: true,
        xfbml: true,
        version: 'v3.0'
      });

      FB.Event.subscribe('auth.statusChange', response => {
        if (response.authResponse) {
          this.checkLoginState();
        } else {
          console.log('[FacebookLoginButton] User cancelled login or did not fully authorize.');
        }
      });
    };
  }

  checkLoginState() {
    FB.getLoginStatus(function(response) {
      this.statusChangeCallback(response);
    }.bind(this));
  }

  login() {
    FB.login(this.checkLoginState(), {
      scope: 'email'
    });
  }

  statusChangeCallback(response) {
    if (response.status === 'connected') {
      this.testAPI();
    } else if (response.status === 'not_authorized') {
      console.log("[FacebookLoginButton] Person is logged into Facebook but not your app");
    } else {
      console.log("[FacebookLoginButton] Person is not logged into Facebook");
    }
  }

  testAPI() {
    FB.api('/me', function(response) {
      console.log('[FacebookLoginButton] Successful login for: ', response);
    });
  }

  render() {
    return ( <
      button className = "btn btn-block btn-fb"
      onClick = {
        () => this.login()
      } >
      <
      i className = "fa fa-facebook" / > Connect with Facebook <
      /button>
    )
  }
}

export default FacebookLoginButton;

나는 이것을 다루기 위해 믹스인 수업을 썼다.

https://github.com/genxstylez/react-oauth-mixin

당신이 자신의 버튼이 아닌 FB의 버튼을 사용하고 싶다면, 이것이 내가 생각할 수 있는 가장 깨끗하고 간단한 방법입니다.

버튼을 사용하는 방법은 이렇게 간단합니다.

<FbLoginBtn
  width="250"
  dataScope="public_profile,email"
  onSuccess={callback}
  onFailure={optionalCallback}
  afterLogin={optionalCallback}
/>

이 컴포넌트는 완전히 자급자족되어 있으며 외부 의존관계에 의존하지 않으며 FB 로그인 버튼 렌더링 이외의 정의된 동작이 없기 때문에 콤포스트성이 매우 뛰어납니다.

import React, { Component } from 'react';

class FbLoginBtn extends Component {
  constructor(props) {
    super(props);

    // post login behavior should be defined at a higher level
    this.onSuccess = this.props.onSuccess || (() => {});
    this.onFailure = this.props.onFailure || (() => {});
    this.onSuccess = this.onSuccess.bind(this);
    this.onFailure = this.onFailure.bind(this);
  }

  componentDidMount() {
    // This is the meat of the component
    // create a script tag, load FB SDK
    // then after script is loaded, set related behavior
    // If you have other components that rely on the FB SDK
    // I recommend extracting this into its own module
    let self = this;
    let scriptTag = document.createElement('script');
    scriptTag.type = 'text/javascript';
    scriptTag.src = "http://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.4&appId=xxxxx";
    scriptTag.addEventListener('load', function (e) {
      self.FB = window.FB;
      // I don't like exposing the SDK to global scope
      window.FB = null;

      // This subscribe the callback when login status change
      // Full list of events is here
      // https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/v2.9
      self.FB.Event.subscribe('auth.statusChange', self.onStatusChange.bind(self));
    });
    document.body.appendChild(scriptTag);
  }

  onStatusChange(response) {
    if (response.status === 'connected') {
      const { accessToken } = response.authResponse;
      // I have a afterLogin optional callback
      // which takes care of ads landing, invitation or any other custom behavior
      this.onSuccess(accessToken, this.props.afterLogin);
    } else {
      this.onFailure();
    }
  }

  render() {
    return (
      <div 
        className="fb-login-button" 
        data-width={this.props.width}
        data-max-rows="1"
        data-size="large"
        data-button-type="login_with"
        data-show-faces="false"
        data-auto-logout-link="true"
        data-use-continue-as="false"
        data-scope={this.props.dataScope}
      >
      </div>
    );
  }
}

export default FbLoginBtn;

늦었을지도 모르지만 @Zoreslav의 답변은 저에게 많은 도움이 됩니다.sdk가 로드되지 않을 때 fb 로그인 버튼으로 로더를 비활성화하거나 추가할 수 있도록 후크로 변환합니다.

import { useState, useEffect, useCallback } from 'react';

const initializeFb = () =>
  // eslint-disable-next-line no-unused-vars
  new Promise((resolve, _reject) => {
    if (typeof FB !== 'undefined') {
      resolve();
    } else {
      // eslint-disable-next-line func-names
      window.fbAsyncInit = function() {
        // eslint-disable-next-line no-undef
        FB.init({
          appId: 'APP ID HERE',
          cookie: true,
          xfbml: true,
          version: 'v2.8',
        });
        // eslint-disable-next-line no-undef
        FB.AppEvents.logPageView();
        resolve();
      };

      // eslint-disable-next-line func-names
      (function(d, s, id) {
        let js;
        const fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {
          return;
        }
        // eslint-disable-next-line prefer-const
        js = d.createElement(s);
        js.id = id;
        js.src = 'https://connect.facebook.net/en_US/sdk.js';
        fjs.parentNode.insertBefore(js, fjs);
      })(document, 'script', 'facebook-jssdk');
    }
  });

const useFacebook = () => {
  const [fb, setFB] = useState([]);
  const [isReady, setReady] = useState(false);

  const initFacebook = useCallback(async () => {
    await initializeFb();
    // eslint-disable-next-line no-undef
    if (typeof FB !== 'undefined') {
      // eslint-disable-next-line no-undef
      setFB(FB);
      setReady(true);
    }
  });

  useEffect(() => {
    initFacebook();
  }, [initFacebook]);

  return [fb, isReady];
};

export default useFacebook;

그럼 이렇게 다른 컴포넌트에서 다시 사용할 수 있습니다.

const Login= ()=>{
    const [FBInstance, isReady] = useFacebook();
    return (<Button onClick()=>{
      FBInstance.getLoginStatus(resp=>{  console.log(resp) })
   }></Button>)
}

react-facebook-login에서 코드를 추출하여 후크를 사용하도록 업데이트했습니다.

import {useEffect, useState} from 'react'

const _extends = Object.assign || function (target) {
    for (let i = 1; i < arguments.length; i++) {
        const source = arguments[i]
        for (const key in source) {
            if (Object.prototype.hasOwnProperty.call(source, key)) {
                target[key] = source[key]
            }
        }
    }
    return target
}

const useFacebook = function () {
    const appId = process.env.NEXT_PUBLIC_FACEBOOK_APP_ID
    const [isReady, setIsReady] = useState(false)

    const facebook = {
        login: async () => {
            const {authResponse, status} = await new Promise(resolve => window.FB.login(resolve, {scope: 'public_profile,email'}))
            if (!authResponse) return {status}

            return new Promise(resolve => window.FB.api('/me', {locale: 'en_US', fields: 'name,email,picture'}, me => {
                _extends(me, authResponse)
                resolve(me)
            }))
        }
    }

    useEffect(() => {
        window.fbAsyncInit = function () {
            FB.init({
                appId,
                autoLogAppEvents: true,
                xfbml: true,
                version: 'v8.0'
            })
            setIsReady(true)
        };

        (function (d, s, id) {
            if (d.getElementById(id)) {
                setIsReady(true)
                return
            }

            const fjs = d.getElementsByTagName(s)[0]
            const js = d.createElement(s)
            js.id = id
            js.src = `https://connect.facebook.net/en-US/sdk.js`
            js.async = true
            js.defer = true
            fjs.parentNode.insertBefore(js, fjs)
        })(document, 'script', 'facebook-jssdk')
    }, [])

    return [facebook, isReady]
}

export default useFacebook

사용방법:

const [facebook, isFacebookReady] = useFacebook()

const handleFacebookLogin = async () => {
  const response = await facebook.login()
  console.log(response)
}

<button type='button' onClick={handleFacebookLogin} disabled={!isFacebookReady}>Login with Facebook</button>

다음 라이브러리를 사용해 보십시오.https://github.com/keppelen/react-facebook-login

매우 간단하게 동작합니다.

import React from 'react';
import ReactDOM from 'react-dom';
import FacebookLogin from 'react-facebook-login';

const responseFacebook = (response) => {
  console.log(response);
}

ReactDOM.render(
  <FacebookLogin
    appId="1088597931155576"
    autoLoad={true}
    callback={responseFacebook} />,
  document.getElementById('demo')
);

아래 간단한 코드 찾기:

import React, { Component } from 'react';
import './App.css';

import FacebookLogin from 'react-facebook-login';

import GoogleLogin from 'react-google-login';

class App extends Component {

render() {

const responseFacebook = (response) => {
console.log(response);
}

const responseGoogle = (response) => {
console.log(response);
}

return (
<div className="App">
<h1>LOGIN WITH FACEBOOK AND GOOGLE</h1>

<FacebookLogin
appId="" //APP ID NOT CREATED YET
fields="name,email,picture"
callback={responseFacebook}
/>
<br />
<br />

<GoogleLogin
clientId="" //CLIENTID NOT CREATED YET
buttonText="LOGIN WITH GOOGLE"
onSuccess={responseGoogle}
onFailure={responseGoogle}
/>

</div>
);
}
}

export default App;

Facebook Javascript SDK for React (Function Components) Devs 。을 함수 에서 "스니펫"을 .fblogin()

react-facebook-login기본 권한보다 더 많은 권한이 필요한 경우 모듈이 작동하지 않습니다.로그인 후 창이 크래시 됩니다.따라서 간단한 FB Auth 통합만 괜찮다면 다음을 수행할 수 있습니다.react-facebook-loginGraph API를 통해 사용자의 Instagram 계정에 액세스해야 한다면 아마 도움이 될 것입니다.

메모: 로그인 상태는 체크되지 않습니다.원하는 경우 추가 스니펫을 추가할 수 있습니다.

여기에 포함시켜 주세요.index.html파일

<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/all.js"></script>

그리고 컴포넌트에 이것을 추가합니다.

//declare a const
const FB = window.FB

async function fbLogin() {
await FB.init({
    appId: '<APP ID>',
    autoLogAppEvents: true,
    xfbml: true,
    version: 'v13.0'       
});

FB.login(function (response) {
    if (response.authResponse) {
        console.log('Welcome!  Fetching your information.... ');
        FB.api('/me', function (response) {
            console.log('Good to see you, ' + response.name + '.');
            console.log('Complete response from Facebook', response)
            FB.getLoginStatus(function (response) {
                if (response.status === 'connected') {
                    let myaccesstoken = response.authResponse.accessToken
                    console.log('Access Token', myaccesstoken)
                }
            });
        });
    } else {
        console.log('User cancelled login or did not fully authorize.');
    }
// mention all your permissions here
}, { scope: 'public_profile,email,pages_show_list,instagram_basic' });

}

그리고 마지막으로 버튼 하나.

<button onClick={() => fbLogin()}>FB Login</button>

언급URL : https://stackoverflow.com/questions/27717555/implement-facebook-api-login-with-reactjs

반응형