Code Monkey home page Code Monkey logo

react-recaptcha's Introduction

react-recaptcha

NPM version Downloads Build Status devDependency Status

NPM

A react.js reCAPTCHA V2 for Google. The FREE anti-abuse service. Easy to add, advanced security, accessible to wide range of users and platforms.

What is reCAPTCHA?

reCAPTCHA is a free service that protects your site from spam and abuse. It uses advanced risk analysis engine to tell humans and bots apart. With the new API, a significant number of your valid human users will pass the reCAPTCHA challenge without having to solve a CAPTCHA (See blog for more details). reCAPTCHA comes in the form of a widget that you can easily add to your blog, forum, registration form, etc.

See the details.

Sign up for an API key pair

To use reCAPTCHA, you need to sign up for an API key pair for your site. The key pair consists of a site key and secret. The site key is used to display the widget on your site. The secret authorizes communication between your application backend and the reCAPTCHA server to verify the user's response. The secret needs to be kept safe for security purposes.

Installation

Install package via node.js

$ npm install --save react-recaptcha

Usage

You can see the full example by following steps.

$ npm install
$ npm start

open the http://localhost:3000 in your browser.

Node support

Node >= v6 is required for this package. Run node -v in your command prompt if you're unsure which Node version you have installed.

Automatically render the reCAPTCHA widget

Html example code:

<html>
  <head>
    <title>reCAPTCHA demo: Simple page</title>
    <script src="build/react.js"></script>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  </head>
  <body>
    <div id="example"></div>
    <script src="build/index.js"></script>
  </body>
</html>

Jsx example code: build/index.js

var Recaptcha = require('react-recaptcha');

ReactDOM.render(
  <Recaptcha
    sitekey="xxxxxxxxxxxxxxxxxxxx"
  />,
  document.getElementById('example')
);

Explicitly render the reCAPTCHA widget

Deferring the render can be achieved by specifying your onload callback function and adding parameters to the JavaScript resource.

<html>
  <head>
    <title>reCAPTCHA demo: Simple page</title>
    <script src="build/react.js"></script>
    <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
  </head>
  <body>
    <div id="example"></div>
    <script src="build/index.js"></script>
  </body>
</html>

Jsx example code: build/index.js

var Recaptcha = require('react-recaptcha');

// specifying your onload callback function
var callback = function () {
  console.log('Done!!!!');
};

ReactDOM.render(
  <Recaptcha
    sitekey="xxxxxxxxxxxxxxxxxxxx"
    render="explicit"
    onloadCallback={callback}
  />,
  document.getElementById('example')
);

Define verify Callback function

var Recaptcha = require('react-recaptcha');

// specifying your onload callback function
var callback = function () {
  console.log('Done!!!!');
};

// specifying verify callback function
var verifyCallback = function (response) {
  console.log(response);
};

ReactDOM.render(
  <Recaptcha
    sitekey="xxxxxxxxxxxxxxxxxxxx"
    render="explicit"
    verifyCallback={verifyCallback}
    onloadCallback={callback}
  />,
  document.getElementById('example')
);

Change the color theme of the widget. Place theme property light|dark. Default value is light.

ReactDOM.render(
  <Recaptcha
    sitekey="xxxxxxxxxxxxxxxxxxxx"
    theme="dark"
  />,
  document.getElementById('example')
);

Change the type of CAPTCHA to serve. Please type property audio|image. Default value is image.

ReactDOM.render(
  <Recaptcha
    sitekey="xxxxxxxxxxxxxxxxxxxx"
    type="audio"
  />,
  document.getElementById('example')
);

Explicitly reset the reCAPTCHA widget

The reCAPTCHA widget can be manually reset by accessing the component instance via a callback ref and calling .reset() on the instance.

var Recaptcha = require('react-recaptcha');

// create a variable to store the component instance
let recaptchaInstance;

// create a reset function
const resetRecaptcha = () => {
  recaptchaInstance.reset();
};

ReactDOM.render(
  <div>
    <Recaptcha
      ref={e => recaptchaInstance = e}
      sitekey="xxxxxxxxxxxxxxxxxxxx"
    />
    <button
      onClick={resetRecaptcha}
    >
     Reset
    </button>
  </div>,
  document.getElementById('example')
);

Component props

Available props

The following props can be passed into the React reCAPTCHA component. These can also be viewed in the source code

  • className : the class for the reCAPTCHA div.
  • onloadCallbackName : the name of your onloadCallback function (see onloadCallback below).
  • elementID : the #id for the reCAPTCHA div.
  • onloadCallback : the callback to pass into the reCAPTCHA API if rendering the reCAPTCHA explicitly.
  • verifyCallback : the callback that fires after reCAPTCHA has verified a user.
  • expiredCallback : optional. A callback to pass into the reCAPTCHA if the reCAPTCHA response has expired.
  • render : specifies the render type for the component (e.g. explicit), see onloadCallback and explicit rendering.
  • sitekey : the sitekey for the reCAPTCHA widget, obtained after signing up for an API key.
  • theme : the color theme for the widget, either light or dark.
  • type : the type of reCAPTCHA you'd like to render, list of reCAPTCHA types available here.
  • verifyCallbackName : the name of your verifyCallback function, see verifyCallback above.
  • expiredCallbackName : the name of your expiredCallbackName function, see expiredCallback above.
  • size : the desired size of the reCAPTCHA widget, can be either 'compact' or 'normal'.
  • tabindex : optional: The tabindex of the widget and challenge. If other elements in your page use tabindex, it should be set to make user navigation easier. More info on tabindex available here.
  • hl : optional. Forces the widget to render in a specific language. Auto-detects the user's language if unspecified. List of language codes available here.
  • badge : optional. Reposition the reCAPTCHA badge. 'inline' allows you to control the CSS.

Default props

If not specified when rendering the component, the following props will be passed into the reCAPTCHA widget:

  {
    elementID: 'g-recaptcha',
    onloadCallback: undefined,
    onloadCallbackName: 'onloadCallback',
    verifyCallback: undefined,
    verifyCallbackName: 'verifyCallback',
    expiredCallback: undefined,
    expiredCallbackName: 'expiredCallback',
    render: 'onload',
    theme: 'light',
    type: 'image',
    size: 'normal',
    tabindex: '0',
    hl: 'en',
    badge: 'bottomright',
  };

Using invisible reCAPTCHA

Use the invisible reCAPTCHA by setting size prop to 'invisible'. Since it is invisible, the reCAPTCHA widget must be executed programatically.

var Recaptcha = require('react-recaptcha');

// create a variable to store the component instance
let recaptchaInstance;

// manually trigger reCAPTCHA execution
const executeCaptcha = function () {
  recaptchaInstance.execute();
};

// executed once the captcha has been verified
// can be used to post forms, redirect, etc.
const verifyCallback = function (response) {
  console.log(response);
  document.getElementById("someForm").submit();
};

ReactDOM.render(
  <div>
    <form id="someForm" action="/search" method="get">
      <input type="text" name="query">
    </form>
    <button
      onClick={executeCaptcha}
    >
     Submit
    </button>

    <Recaptcha
      ref={e => recaptchaInstance = e}
      sitekey="xxxxxxxxxxxxxxxxxxxx"
      size="invisible"
      verifyCallback={verifyCallback}
    />
  </div>,
  document.getElementById('example')
);

Contributing

    1. Fork it
    1. Create your feature branch (git checkout -b my-new-feature)
    1. Commit your changes (git commit -am 'Add some feature')
    1. Push to the branch (git push origin my-new-feature)
    1. Create new Pull Request

react-recaptcha's People

Contributors

2fort avatar ajprax avatar andyfry01 avatar appleboy avatar boomxx avatar chentsulin avatar danbahrami avatar dependabot[bot] avatar elecweb avatar evenchange4 avatar geoffrey avatar ghengeveld avatar greenkeeperio-bot avatar hbowden avatar hvolschenk avatar jeffmicklos avatar johngeorgiadis avatar joxertmd avatar louisebc avatar meganoob1337 avatar navarroaxel avatar pika-shi avatar roberthodgen avatar robertomsousa avatar sergiop avatar vinceve 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

react-recaptcha's Issues

onRequestBegin config option

The new methods in BaseModel does not have an option to pass a token in the request header. I already have code for BaseModel - create which sets the session token in the request header.

BaseModel.addClassAction("create", function(attributes = {}) {
    API.requestHeaders[HEADER_SESSION_TOKEN] = authProvider.fetchToken();
    return API.request({
        method: "post",
        data: { resource: [attributes] },
        endpoint: this.urlRoot
    });
});

The above code will break if I upgrade mobx-model. To prevent too much of code rewrite, I propose adding another config option - onRequestBegin.

  config(options = {}) {
    Object.assign(this, pick(options, [
      'onRequestBegin',
      'onRequestError',
      'onRequestCompleted',
      'requestData',
      'requestHeaders',
      'urlRoot',
      'superagent'
    ]))
  },

onRequestBegin will be triggered before making the API call. With this change, I will be able to upgrade to the latest 0.32.

Error on multiple recaptchas per page

Thank you for creating this component,
I want to use more than one recaptcha on the same page, but i am getting an error:

screenshot from 2017-05-26 14 31 34

the code that i am using is:

<Recaptcha sitekey='XXXX' render='explicit' verifyCallback={this.captchaVerify} onloadCallback={this.captchaOnload} />

What am i doing wrong?

Help Needed : react-recaptcha Test Case using enzyme

I have implemented react-recaptcha. I am trying to generate test cases for the same. where i am able to find the captcha control but not able to simulate its select value.

Please let me know if anybody has done.

Thanks.

Reset method isn't working

I tried to use the reset method with the only captcha that I had in my page and It's showing me this error:

Invalid ReCAPTCHA client id: 0

How to use it in a web form?

I want to know how to implement it in a Form
I need to use it and validate it as a require field

I don't know how to

Missing unminified version from npm

When I install via npm, I have only this minified file:

node_modules/react-recaptcha/dist/react-recaptcha.js

I usually expect to have both a minified and unminified version, like this:

node_modules/react-recaptcha/dist/react-recaptcha.js
node_modules/react-recaptcha/dist/react-recaptcha.min.js

How to config language on ReCAPTCHA component?

I run my app on local with

<script src="https://www.google.com/recaptcha/api.js?hl=ja" async defer></script>

so, language of recaptcha is Japanese.
However, i run on dev environment, it show English.

Recaptcha doesn't fully render to DOM

When using recaptcha inside JSX, Recaptcha is not fully rendered. Div is blank.

<div class="g-recaptcha" data-sitekey="my-own-tested-and-valid-key" data-theme="light" data-type="image" data-size="normal" data-tabindex="0" data-reactid=".1.0.1.3"></div>

react-recaptcha is imported and rendered as <Recaptcha sitekey="my-own-tested-and-valid-key" />

react-recaptcha Test Case using enzyme

I have implemented react-recaptcha. I am trying to generate test cases for the same. where i am able to find the captcha control but not able to simulate its select value.

Please let me know if anybody has done.

Thanks.

ReCAPTCHA placeholder element must be an element or id

I got the error when inflating the view by code below:

     <div className="form-group" id="captcha-holder">
        <Recaptcha sitekey="xxx" render="explicit" verifyCallback={this.onCaptchaVerify}/>
    </div>
recaptcha__en.js:286 Uncaught Error: ReCAPTCHA placeholder element must be an element or id

How do I get the response from Inside my class

Basically I'm trying to validate the response from inside my _onSubmit() function is this possible I've tried moving the callback function inside the class so i could use setState or something but Recaptcha fails to locate the function if i put it inside the class.

I'm thinking maybe the better idea is to probably is to check the validation server side right? I'm probably implementing recaptcha wrong trying to handle everything client side?

  class ContactForm extends React.Component{
  constructor(){
    super();
    this._onSubmit = this._onSubmit.bind(this);
  }

  _onSubmit(e){
    //I WANT TO VALIDATE THE RESPONSE HERE
  }

  render(){
    return(
     <form className="form-horizontal" onSubmit={this._onSubmit} >
      <Recaptcha sitekey="*****" render="explicit" verifyCallback={captchaReturn} onloadCallback={onloadCallback} />

      <button type="submit" id="myBtn" disabled="true" className="btn btn-default">Submit</button>
    </form>
    );
  }
}

let captchaReturn = function(response){
  if(response.length === 0){
    alert("no");
  }
  else {
    document.getElementById("myBtn").disabled = false;
  }
}

let onloadCallback = function() {

}

should compile to js instead of jsx

if we require this one in webpack or something like that it will be fail.

I think it should convert jsx to js file to be working in more environment.

/*
/private/var/clones/interest_workspace/budget/node_modules/react-recaptcha/src/index.js:41
<div id={this.props.elementID}
^
SyntaxError: Unexpected token <
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Module._extensions..js (module.js:478:10)
at Object.require.extensions.(anonymous function) [as .js] (/private/var/clones/interest_workspace/budget/node_modules/babel-core/lib/api/register/node.js:214:7)
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. (/private/var/clones/interest_workspace/budget/views/controller/user/signup.jsx:3:65)
at Module._compile (module.js:460:26)
*/

for how to convert, here's a simple tool
https://goo.gl/mxKebV

Pre commit broken on Windows.

I'm trying to create a few pull requests but the pre-commit hook is broken for me. I looked in the package.json and I see the pre-commit runs lint and test. I ran those commands individually and they both pass but I can't commit with git in this repo. Below is the results of running lint and test then trying to commit. The very bottom of the image is the error message I am receiving.

pre-commit-hook

It appears that pre-commit is broken on Windows: observing/pre-commit#102

Can we remove the pre-commit hook and let CI take care of that? Because this repo is mostly unusable on Windows in it's current state.

Limited test coverage

Hi again!

The test cases in the test spec aren't very robust, basically consisting of a single 'it should exist' test.

I'd be glad to do a PR with some more test cases to improve coverage for the component.

๐Ÿ—

Multiple Instances

I have 2 separate modals and want to use reCaptcha in each.

I am able to successfully render reCaptcha in 1 modal but am not able to render both.

How do I render multiple instances of reCaptcha ?

Issue solved:

Define elementID(as prop of reCaptcha component) of each individual instance.

Race condition for explicit rendering

Sometimes your component will register the onloadCallback function in window after api.js loads, so the callback is never called and the component never loads.

Using the normal rendering method is technically a race condition as well, since React may load after Recaptcha looks for the div element, but I haven't seen this happen yet in practice.

Render recaptcha script only inside the Recaptcha component

For now, one should add the Google re-captcha script into the project's HTML and add it globally in order for re-captcha to be rendered fully.
If we could load the script dynamically when the Recaptcha component mounts, that would be really awesome since the script is always the same and Using script tag in JSX won't work properly.

For rendering only once, one could use:

class LazyLoadedRecaptcha extends React.Component {
  componentDidMount() {
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.defer = true;
    script.src = "https://www.google.com/recaptcha/api.js"
    this.refs.addScriptHere.appendChild(script);
  }
  
  render() {
    return (<div class="lazy-recaptcha" ref="addScriptHere" />);
  }
}

This would solve the issue mentioned on #147 as well.

Would be happy to send the PR!

Instructions on how to build dist?

Hi, just a question on how to go about building 'dist'

When I run 'npm run compile' I get a dist that includes object-assign and modernizr. How would I go about building to produce a dist output that is the same format as distributed by the npm module?

Thanks,
Eric

onloadCallback error if no onloadCallback function provided

Getting the following in the console when no onloadCallback function is provided to the control:

Uncaught TypeError: this.props.onloadCallback is not a function

I don't seem to need one for my use case, and therefore this looks like a bug. There are a few spots in the code where there seems to be tests whether this is defined before it is used (e.g. componentDidUpdate), but not in _renderGrecaptcha().

Available props

Please include all available props to your documentation. I broke my brain trying to set proper lang to recaptacha. Official google documentation says to add hl param to script path, but that does not work, thanks to your line number 103 at index.js! I agree! It is correct way to set params like that, but how in world i would know that from your readme... gosh...

i m really sorry for yelling... i've had a deadline today, hopefully it will pass successfully...

Anyway, thanks for your plugin!
best wishes)

react/addons is deprecated

Warning:

Warning: require('react/addons') is deprecated. Access using require('react-addons-{addon}') instead.

Refreshing page causes 'graptcha not defined' error

I am using react-router in my project with redux, and everything works when navigating normally. However when a user refreshes the page with the captcha on it, 3/4 times I get:
grecaptcha is not defined

I think this is race condition because, when I work locally, I do not get this error. Here's how I have my code setup:
index.html

<head>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
</head>

Signup.jsx

<Recaptcha {...captcha} sitekey='xxx-xxx-xxx'  
     render = 'explicit'  
     verifyCallback={this.verifyCallback}  
     data-size="compact"  
     onloadCallback={this.captchaLoadCallback}  
     style={this.captchaStyle}  
     size='small' />  
...

Any ideas?

Example does not run

ERROR in ./example/main.js
Module parse failed: /home/sudheer/workspace/react-recaptcha-test/node_modules/react-recaptcha/example/main.js Unexpected token (25:6)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (25:6)
at Parser.pp.raise (/home/sudheer/workspace/react-recaptcha-test/node_modules/react-recaptcha/node_modules/webpack/node_modules/acorn/dist/acorn.js:923:13)
at Parser.pp.unexpected (/home/sudheer/workspace/react-recaptcha-test/node_modules/react-recaptcha/node_modules/webpack/node_modules/acorn/dist/acorn.js:1490:8)
at Parser.pp.parseExprAtom (/home/sudheer/workspace/react-recaptcha-test/node_modules/react-recaptcha/node_modules/webpack/node_modules/acorn/dist/acorn.js:333:12)
at Parser.pp.parseExprSubscripts (/home/sudheer/workspace/react-recaptcha-test/node_modules/react-recaptcha/node_modules/webpack/node_modules/acorn/dist/acorn.js:228:19)
at Parser.pp.parseMaybeUnary (/home/sudheer/workspace/react-recaptcha-test/node_modules/react-recaptcha/node_modules/webpack/node_modules/acorn/dist/acorn.js:207:17)
at Parser.pp.parseExprOps (/home/sudheer/workspace/react-recaptcha-test/node_modules/react-recaptcha/node_modules/webpack/node_modules/acorn/dist/acorn.js:154:19)
at Parser.pp.parseMaybeConditional (/home/sudheer/workspace/react-recaptcha-test/node_modules/react-recaptcha/node_modules/webpack/node_modules/acorn/dist/acorn.js:136:19)
at Parser.pp.parseMaybeAssign (/home/sudheer/workspace/react-recaptcha-test/node_modules/react-recaptcha/node_modules/webpack/node_modules/acorn/dist/acorn.js:112:19)
at Parser.pp.parseParenAndDistinguishExpression (/home/sudheer/workspace/react-recaptcha-test/node_modules/react-recaptcha/node_modules/webpack/node_modules/acorn/dist/acorn.js:376:28)
at Parser.pp.parseExprAtom (/home/sudheer/workspace/react-recaptcha-test/node_modules/react-recaptcha/node_modules/webpack/node_modules/acorn/dist/acorn.js:307:19)
@ multi main
webpack: bundle is now VALID.

v.2.2.0 bundle includes react source code

Hi,
I think 2.2.0 bundle includes React source and maybe something else. I updated the library and my application isn't working anymore.

I compared the bundles:

2.1.1: 3Kb
2.2.0: 176Kb

I tried to look for something in past commits but I can't seem to find anything. I guess something went wrong before publishing to npm.

React Router

This components does not appear to work between routes, if its the default route it seem to work ok but navigating between routes it does not appear to work. Is there something I need to reset in the route to make it work.

Localization is not working in latest version 2.3.2 backward compatibility of 2.2.6 is broken

Hi Localisation is not working in your latest version : 2.3.2 and it breaks in our production environment.

Here is the steps to reproduce the issue.

  1. Pass locale in google captcha . For ex hl=fr_fr in url - https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&hl=fr_fr'.

  2. I see that google captacha is always loading with en_us locale.

When i change the version to 2.2.6, then it started working. Request you look into this issue and let us know ASAP else will remove this lirary from our project.

Here is sample code for your reference -
class GoogleRecaptche extends Component {
constructor(props) {
super(props);
const locale = window.json && window.json.locale ? window.json.locale : "fr-fr";
recaptcha.src = 'https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&hl='+locale;
document.head.appendChild(recaptcha);
}
render (
return () {
<Recaptcha
ref={e => this.recaptchaInstance = e}
sitekey={sitekey}
render="explicit"
verifyCallback={this.verifyCallback}
onloadCallback={this.callback}
expiredCallback={this.expiredCallback}
/>
}
}

Thanks,
Reetesh

Passing style prop

Can I pass style prop to <Recaptcha />? I want to give it margin: auto.

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.