Code Monkey home page Code Monkey logo

react-facebook-login's Introduction

React Facebook Login - Build Status

A Component React for Facebook Login

Getting Started

  • yarn add react-facebook-login or npm install react-facebook-login
  • Your application will also need react-dom and react installed.

Development

git clone https://github.com/keppelen/react-facebook-login.git && cd react-facebook-login
npm install react react-dom react-facebook-login --save --force
npm start

How to use

Basic button with styling

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}
    fields="name,email,picture"
    onClick={componentClicked}
    callback={responseFacebook} />,
  document.getElementById('demo')
);

Facebook button without styling

If you're providing all your own custom styling, you can use the render prop build. This build doesn't include any CSS or additional code needed to customise the look of the button, and instead leaves that entirely up to you. You can see an example of this in demo/index.js.

To make sure you import the right version, you will need to update your import line:

import FacebookLogin from 'react-facebook-login/dist/facebook-login-render-props'
<FacebookLogin
  appId="1088597931155576"
  autoLoad
  callback={responseFacebook}
  render={renderProps => (
    <button onClick={renderProps.onClick}>This is my custom FB button</button>
  )}
/>

The render function will be passed the following properties for you to use:

  • onClick
  • isDisabled
  • isProcessing
  • isSdkLoaded

Custom CSS Class and Icon

By default fontawesome is included, If you don't want to use default fontawesome icons, you can send an element in icon attribute

Fontawesome example:

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}
    fields="name,email,picture"
    callback={responseFacebook}
    cssClass="my-facebook-button-class"
    icon="fa-facebook"
  />,
  document.getElementById('demo')
);

Custom element example:

import React from 'react';
import ReactDOM from 'react-dom';
import FacebookLogin from 'react-facebook-login';
import TiSocialFacebookCircular from 'react-icons/lib/ti/social-facebook-circular';

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

ReactDOM.render(
  <FacebookLogin
    appId="1088597931155576"
    autoLoad={true}
    fields="name,email,picture"
    callback={responseFacebook}
    cssClass="my-facebook-button-class"
    icon={<TiSocialFacebookCircular />}
  />,
  document.getElementById('demo')
);

Custom permission

By default the component, request only 'public_profile' permission, you can change if you send 'scope', that is a string comma separated attribute.

see https://developers.facebook.com/docs/facebook-login/permissions for permissions list

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

  class MyComponent extends React.Component {
    responseFacebook(response) {
      console.log(response);
    }

    render() {
      return (
        <FacebookLogin
          appId="1088597931155576"
          autoLoad={true}
          fields="name,email,picture"
          scope="public_profile,user_friends,user_actions.books"
          callback={this.responseFacebook}
        />
      )
    }
  }

  export default MyComponent;

Server

'use strict';

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

class MyComponent extends React.Component {
  responseFacebook(response) {
    console.log(response)
  }

  render() {
    return (
      <FacebookLogin
        appId="1088597931155576"
        autoLoad={true}
        fields="name,email,picture"
        callback={this.responseFacebook}
      />
    )
  }
}

export default MyComponent;

Parameters

params value default value
appId string Required
size string small - medium - metro
scope string public_profile, email, user_birthday
fields string name,email,picture
callback function resultFacebookLogin
returnScopes boolean false
autoLoad boolean false
xfbml boolean false
cookie boolean false
textButton string Login with Facebook
cssClass string kep-login-facebook kep-login-facebook-[button-size]
redirectUri string window.location.href (mobile-only)
version string 3.1
icon string element
language string en_US
onClick function Initial click on the component
isMobile boolean detected via userAgent
disableMobileRedirect boolean false
isDisabled boolean undefined
tag string HTML Element, Ex: 'a', 'button'
onFailure function optional function to separatere the failed init
state string optional string to maintain state between the request and callback. This parameter should be used for preventing Cross-site Request Forgery and will be passed back to you, unchanged, in your redirect URI
authType string optional string to change authentication type
responseType string optional string to change response type. Default value is 'code'

react-facebook-login's People

Contributors

adrianobel avatar andrewkamphuis avatar anthonyjgrove avatar arabold avatar arekrado avatar aryk avatar chl03ks avatar cristiancedenogallego avatar daikikohara avatar davidan90 avatar devalien avatar fmy avatar goldylucks avatar greyvugrin avatar gustavodinizmonteiro avatar hammster avatar hinderberg avatar inakiabt avatar jackfranklin avatar januszp avatar jtokoph avatar keppelen avatar mrdivyansh avatar samuxyz avatar sterlingvix avatar tobitos avatar tonyalaribe avatar veddermatic avatar williamboman avatar zebapy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-facebook-login's Issues

How the icon property works ?

Hello

It's not clear how the icon property works ?

It's seems to need font-awesome right ?

Do we have to include it ourself ? If so, please mention it in the documentation.

Best regards

error: FB.login() called before FB.init()

Seems to be related to reauthenticate.
Setting reauthenticate={false} and changing settings for autoLoad don't seem to make a difference.
This issue doesn't appear in 3.2.0

add feature: to perform some action before calling login api

need a feature: on button click, perform some user actions then call the login api.

something like:

<FacebookLogin icon="fa fa-facebook"  beforeAction={this._onClick}
         scope={this.state.fb_scope} fields={this.state.fb_fields}
         appId={this.state.fb_id} autoLoad={false} callback={this._onFBResponse} />

Facebook popin appears 2 times when cancel

Hello

After calling the Facebook authentication popin, I click on the cancel button.

The popin closed but another Facebook authentication popin appears.

Best regards

"Sorry, something went wrong" on facebook dialog window

After click on login component the facebook dialog window is opened and show this message:

"
Sorry, something went wrong.

We're working on getting this fixed as soon as we can.

Go Back
"

Anyone knows what's wrong?

thanks

fb_screen_shot

Getting username of logged in user.

Hi, I am able to get userid, name, email, profile picture of user, which is pretty good. Is there any way to get username also of the logged in facebook user. Or please suggest me the best way to get username of the logged in user.

[BABEL] Unknown option: base.stage

Cloned the project, installed what was needed, and npm started.

This comes up

ERROR in ./demo/index.js
Module build failed: ReferenceError: [BABEL] /home/seba/repos/test_applications/react-facebook-login/demo/index.js: Unknown option: base.stage

White Screen on login with facebook in iOS webapp

First thank you for your work on this project. Is has been very helpful.

I have a web application that works great on desktop and mobile. I am trying to now make it into a web app (when users presses share in mobile safari browser, then save link to iOS home screen).

A web app is easily created by adding a few link tabs in the header section as such:

  <link rel="apple-touch-icon" sizes="57x57" href="appIcon_57x57-1.png" />
  <link rel="apple-touch-icon" sizes="80x80" href="appIcon_80x80.png" />
  <link rel="apple-touch-icon" sizes="87x87" href="appIcon_87x87.png" />
  <link rel="apple-touch-icon" sizes="114x114" href="appIcon_114x114.png" />
  <link rel="apple-touch-icon" sizes="120x120" href="appIcon_120x120.png" />
  <link rel="apple-touch-icon" sizes="180x180" href="appIcon_180x180.png" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-title" content="MY APP">

The issue is that when I login via the web app I am getting a white screen as others have documented (with workarounds) in the following stackoverflow links.

Best overview of solution:
stack 11197668

Others:
stack 8019798

stack 11293494

In facebook.js the following code is only checking for mobile chrome.

 click = () => {
    const { scope, appId } = this.props;
    if (navigator.userAgent.match('CriOS')) {
      window.location.href = `https://www.facebook.com/dialog/oauth?client_id=${appId}&redirect_uri=${window.location.href}&state=facebookdirect&${scope}`;
    } else {
      window.FB.login(this.checkLoginState, { scope });
    }
  };

By changing the userAgent check as a merging of the different stack overflow solutions I have the following hybrid solution that works for me. Perhaps this can be reviewed, edited, improved on, put into the next release?

  click = () => {
    const { scope, appId } = this.props;
    var isMobile = false;
    try {
        isMobile = ((window.navigator&&window.navigator.standalone)||navigator.userAgent.match('CriOS')||navigator.userAgent.match('mobile'));
    } catch (e) {}
    if ( isMobile ) {
      window.location.href = `https://www.facebook.com/dialog/oauth?client_id=${appId}&redirect_uri=${window.location.href}&state=facebookdirect&${scope}`;
    } else {
      window.FB.login(this.checkLoginState, { scope });
    }
  };

Thank you,
Bret

Cookies

Is there anyway to disable the automatic Facebook request from the cookie? I can't find it in the docs.

Should add a feature to return the original response object received

Hi @keppelen - Firstly, its really great that you have built this react FB login component.
Well, the issue I'm raising is two-fold:

  1. The documentation today does not clearly define what is the response received by the callback 'responseFacebook'. Looking at the underlying code, I see it is either the response.status if it is a failed login attempt OR then it is a new object of the result of the "me" combined with response.authResponse.
  2. It's great that you have provided your custom implementation to handle those responses but if someone is building their own login flows and maintaining their own state in using redux, it can be limiting in some ways as they would need the original response object received from the actual FB.getLoginStatus() call. Having said that, can a new boolean prop (say) "origResponse" be added to the component in order to simply return the original response object so the user can do their own login state management?

strange error "Cannot read property 'login' of undefined(…)"

Hi. Sometimes i get this error. Error is located here window.FB.login(r.checkLoginState. So, i supposed it appears when FB scripts didn't finish loading. When i give it more time and push login button after 30 sec it definetly works correct.
How can i avoid this? maybe i can prevent callback execution until it finish loading?
and thanks for cood project

Why the button is wrapped inside span tags?

I am trying to use this login and it works fine, except for the fact that my styling breaks, due to span, is there a reason to use span?
moreover is there a way so that I can just export the click method and use it with any button as I see fit?

Make demo on github pages

The purpose of the demo is to let developers test quickly the package without downloading it

I can add an after_success script that will build latest master and push it to gh-pages

The demo will be a simple page with inputs for all the props the button supports

@keppelen what r your thoughts?

Custom button design

Hi, is it possible to remove predefined styles and put some custom class for the button, even better just to provide some way to use custom template. In my case I will need to use different tag, classes, and icon inside the button.

Stop form submission on click

Placing this button inside a form submits the form on click. Do you think it's the responsibility of the component to deal with that or the surrounding form?

Scope seems to have no effect when used via click event

The scope data isn't returned from /me when called after login via the click handler (explicit FB.login).
I've changed the code to explicitly ask for the scope fields and this seems to work. e.g.

FB.api("/me?fields=id,first_name,last_name,link,gender,locale,timezone,email", ....)

Not sure if this is a version API issue, or an app config problem. I seem to remember it used to work.

Error with peerDependencies when install

Stack:

  • npm v2.14.7
  • node v4.2.2
npm ERR! Darwin 15.5.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "react-facebook-login" "--save"
npm ERR! node v4.2.2
npm ERR! npm  v2.14.7
npm ERR! code EPEERINVALID

autoload not working properly

Hello,
I'm using a simple callback for my FacebookLogin. It basically sets a variable to true if the response is "connected". I have autoLoad on, and my callback is being called as soon as the component is loaded, but the response on autoLoad is always "unknown". Even though when I press the button I'm instantly logged in (prompt doesn't ask for username and password again unless I use FB.logout()) which means that autoLoad should get back a "connected" response.

Am I missing something?
Thanks

Don't check in minified javascript

It is a security risk using a library to handle something sensitive like login when it has been obfuscated on someone else's machine.

Error after Install

Any idea why it can't see React variable?

cument.getElementById("facebook-login"))},function(e,t,n){e.exports=React},fun
^
ReferenceError: React is not defined
at Object. (/Users/Ryeguy/Documents/Projects/Books/node_modules/react-facebook-login/dist/facebook-login.js:1:578)
at t (/Users/Ryeguy/Documents/Projects/Books/node_modules/react-facebook-login/dist/facebook-login.js:1:169)
at Object.e.exports (/Users/Ryeguy/Documents/Projects/Books/node_modules/react-facebook-login/dist/facebook-login.js:1:326)
at t (/Users/Ryeguy/Documents/Projects/Books/node_modules/react-facebook-login/dist/facebook-login.js:1:169)
at /Users/Ryeguy/Documents/Projects/Books/node_modules/react-facebook-login/dist/facebook-login.js:1:284
at Object. (/Users/Ryeguy/Documents/Projects/Books/node_modules/react-facebook-login/dist/facebook-login.js:1:289)
at Module._compile (module.js:460:26)
at Object.require.extensions.(anonymous function) as .js
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object. (/Users/Ryeguy/Documents/Projects/Books/components/header.react.js:6:16)
at Module._compile (module.js:460:26)
at Object.require.extensions.(anonymous function) as .js
at Module.load (module.js:355:32)

Throwing warnings when including it in a project

This is a sample trace of the warning messages:

./~/react/react.js
There is another module with an equal name when case is ignored.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Rename module if multiple modules are expected or use equal casing if one module is expected.
client:37 ./~/React/react.js
There is another module with an equal name when case is ignored.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Rename module if multiple modules are expected or use equal casing if one module is expected.

No cookie is set

Login works perfect but there is no cookie set for my php-script to fetch after callback?

version 3.4.0

<FacebookLogin
          appId="{}"
          autoLoad={false}
          cookie={true}
          scope='public_profile,email,user_friends'
          fields="name,email,picture"
          onClick={this.getCurrentUser}
          icon="fa-facebook"
          callback={this.props.store.loginWithFacebook} 
/>

SOLVED!
I found that chrome does not accept cookies on localhost. It all worked in firefox.

Logout

It would be nice to have the ability to logout as well
it seems like adding data-auto-logout-link="false" might do it

Fb logout

Great work here. How would i go about setting up Logout?

textButton props should accept React.PropTypes.element

Hi

I got the following warning :

 Failed propType: Invalid prop `textButton` of type `object` supplied to `t`, expected `string`.

It is because I use react-intl to give the textButton props value :

<FacebookLogin
        textButton={ <FormattedMessage
            id="auth.facebook.login.button.label"
            description="Facebook login button label"
            defaultMessage="Login with Facebook"/> }
    />

I think textButton props should also accept React.PropTypes.element :

textButton: React.PropTypes.oneOfType([
        React.PropTypes.string,
        React.PropTypes.element
    ])

Best regards

changing styles

Hi, im trying to change the color and size of the button. When i change these styles in the facebook.scss file, it does not change. for example, if i change to yellow the button stays blue. tks

$font-family-default: 'Helvetica', sans-serif;

@function calc-responsive($value1, $width1, $value2, $width2) {
$x1: $width1;
$x2: $width2;
$y1: $value1;
$y2: $value2;
$a: ($y2 - $y1) / ($x2 - $x1);
$b: ($x2 * $y1 - $x1 * $y2) / ($x2 - $x1);
@return calc(#{$a_100vw} + #{$b_1px});
}

%button {
font-family: $font-family-default;
font-weight: bold;
-webkit-font-smoothing: antialiased;
border-width: 2px;
border-style: solid;
color: #FFF;
cursor: pointer;
display: inline-block;
font-size: calc-responsive(12, 768, 18, 1920);
text-decoration: none;
text-transform: uppercase;
transition: background-color .3s, border-color .3s;
background-color: yellow;
border-color: yellow;
}

.small {
@extend %button;
padding: 1.2em 3em;

@media (min-width: 768px) {
padding: 0.9em 2.2em;
}
}

.medium {
@extend %button;
padding: 1.2em 3em;

@media (min-width: 768px) {
padding: 1.6em 2.4em;
}
}

.metro {
@extend %button;
border-radius: 0;
}

Blank popup when revisiting page that has the button

The button works fine when you first load the page and log in with it. The issue is when you visit a react page that has the button, go to another page, then revisit that page with the button, I'm getting the popup for the facebook auth but it is blank and just hangs. Is this an issue with my Facebook app settings or this module?

Cannot use react style parameter

Does this component support passing in the style parameter like most react components? We use it to dynamically set our image server host from env variables.

<FacebookLogin
              appId={process.env.FACEBOOK_ID}
              autoLoad={false}
              textButton="Log in with Facebook"
              fields="email"
              callback={this.responseFacebook}
              version="2.7"
              cssClass="btn icon-btn btn-block space-1 signup-login-form__btn-xl btn-large btn-facebook"
              style={{backgroundImage: `url(${process.env.IMAGE_HOST}facebook-icon.svg)`}}
            />

Different behavior in mobile

Hi, my login works perfect when sign in through a desktop browser. But on mobile device it's redirects with url with tokens, my js-callback is never triggered.

what data to store in db?

Hi

It would be great to get a bit more info on what is being returned. Like what is the best "id" to store for later lookup?

Error: 'undefined is not a function', on chrome 36

On chrome version 36, 38, 39, getting an error, "undefined is not a function" and callback is not getting called.
This error occurs after login into facebook.
Looking at the issue it seems like it is not able to find the callback function when it is already defined.
It is working fine on new chrome versions, 50,51,52,54

<FacebookLogin
textButton="LOGIN WITH FACEBOOK"
cssClass="tUpper action-button"
icon="fa-facebook-official"
appId={Application.settings.facebookAppId}
autoLoad={false}
fields="name,email,picture"
callback={this.responseFacebook.bind(this)}
onFailure={function(error) {
console.log('error '+ error);
}
}
/>`

FB.* is not a function!

Hi,

I get FB.login is not a function or FB.getLoginStatus is not a function. The FB.api doesn't give this error but it doesn't produce any response either.

Thank You!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.