GithubHelp home page GithubHelp logo

mukeshsoni / react-telephone-input Goto Github PK

View Code? Open in Web Editor NEW
266.0 7.0 167.0 20.79 MB

React component for entering and validating international telephone numbers

Home Page: https://unstack.in/react-telephone-input

License: MIT License

JavaScript 20.59% CSS 19.34% HTML 0.78% TypeScript 26.64% Less 32.65%
react react-component international-telephone input

react-telephone-input's Introduction

Reactjs Component for International Telephone Input

Travis npm package

IMP: From 5.*, the withStyles file will not be bundled in dist. If you want to use the css, you can import the css file directly to your module -

import 'react-telephone-input/css/default.css'

IMP: From 3.*, the styles won't be included by default. Can use require('react-telephone-input/lib/withStyles') to get the styles.

Inspired from the awesome jquery plugin for International Telephone Input.

This one is written as a reactjs component.

Live Demo here - http://unstack.in/react-telephone-input/

How it looks

function handleInputChange(telNumber, selectedCountry) {
    console.log('input changed. number: ', telNumber, 'selected country: ', selectedCountry);
}

// Use declaratively within another react components render method
var ReactTelInput = require('react-telephone-input');
// var ReactTelInput = require('react-telephone-input/lib/withStyles'), if you need the styles

<MyAwesomeReactComponent>
  <ReactTelInput
        defaultCountry="in"
        flagsImagePath='/path/to/images/flags.png'
        onChange={handleInputChange}
        onBlur={handleInputBlur}
        />
</MyAwesomeReactComponent>

// or render standalone
var ReactTelInput = require('react-telephone-input');
React.render(<ReactTelInput
                defaultCountry="in"
                flagsImagePath='/path/to/images/flags.png'
                onChange={handleInputChange}
                onBlur={handleInputBlur}
              />,
              document.getElementById('my-container'));

The component accepts other props to customize it -

value and initialValue

Both the props have the same purpose - for setting the initial value of the input programatically.

initialValue

See value above.

autoFormat

true by default. Setting it to false will turn off all auto formatting.

defaultCountry

The component selects the country code of a country by default. You can change it by passing the iso2 name of a country. E.g. for United States, set defaultCountry to 'us'.

onlyCountries

If you don't want all countries to be shown in the dropdown list, you can pass an array of objects representing the countries. The structure of each country object can be seen here https://github.com/mukeshsoni/country-telephone-data/blob/master/country_telephone_data.js

E.g.

<ReactTelInput
    defaultCountry='us'
    value={value}
    onChange={onPhoneChange}
    onlyCountries={[
        {name: "United States", iso2: "us", dialCode: "1", priority: 0, format: "+. (...) ...-...."},
        {name: "Canada", iso2: "ca", dialCode: "1", priority: 1, format: "+. (...) ...-....", hasAreaCodes: true},
        {name: "Mexico (México)", iso2: "mx", dialCode: "52", priority: 0, format: "+..-..-..-...."},
        {name: "Brazil (Brasil)", iso2: "br", dialCode: "55", priority: 0, format: "+..-..-....-...."},
    ]}
 />

preferredCountries

Preferred countries show up at the top of the list. This prop also accepts an array of country iso2 names.

E.g.

<ReactTelephoneInput
  preferredCountries={['in', 'us', 'gb']}
  />

classNames

You can send in additional classes to be applied to the top container div of the component.

onChange

Function, which is called whenever there is a change of value in the input box.

onEnterKeyPress

Function, which is called when user presses the 'enter' key when the input box is in focus.

onBlur

Function, which is called when the focus goes away from the input box.

onFocus

Function, which is called when the input box gets the focus.

disabled

Boolean value. When set to true, the input box is disabled and clicking on flag dropdown does nothing.

pattern

String. This is passed on to the input field and works like it should for any other input field.

inputProps

Object. If you want to set some property on the input element, you can pass in an object with attributes. E.g.

let inputProps={
    readOnly: true,
    autoFocus: true
}

<ReactTelephoneInput inputProps={inputProps} ... />

autoComplete

string. Specify the type of autocomplete for the input element.

Default value - 'tel'

listStyle

Object. Style applied to the dropdown list container. There is a default value for it

listStyle = {
  zIndex: 20,
  backgroundColor: 'white'
}

listItemClassName

string. Classname which will be applied to each item in the dropdown list. The default is country

How to use it

  • If you install it from npm install, you can just do var ReactTelephoneInput = require('react-telephone-input');
  • You will need to copy flags.png from example/src folder to see the flag icons for each country.
  • Set the path to the flags image using the prop flagsImagePath
function handleInputChange(telNumber, selectedCountry) {
  console.log('input changed. number: ', telNumber, 'selected country: ', selectedCountry)
}

function handleInputBlur(telNumber, selectedCountry) {
  console.log(
    'Focus off the ReactTelephoneInput component. Tel number entered is: ',
    telNumber,
    ' selected country is: ',
    selectedCountry
  )
}

<ReactTelephoneInput
  defaultCountry="in"
  flagsImagePath="/path/to/images/flags.png"
  onChange={handleInputChange}
  onBlur={handleInputBlur}
/>

The default value for flagsImagePath is 'flags.png'

Features

  • Automatically format the number as the user types
  • Navigate the country dropdown by typing a country's name, or using up/down keys
  • Selecting a country from the dropdown will update the dial code in the input
  • Typing a different dial code will automatically update the displayed flag
  • Country names in the dropdown also include localised versions in brackets
  • Dropdown appears above or below the input depending on available space/scroll position

Contributing

You can try the app by downloading everything and running the commands given below -

$ npm install
$ npm start

go to your browser and type http://localhost:3000

Running tests

$ npm run test
$ npm run test -- --watch # to run tests in watch mode

react-telephone-input's People

Contributors

ahstro avatar alelb avatar brunops avatar colmhally avatar dependabot-preview[bot] avatar dmnd avatar fredppm avatar jaredsohn avatar jeltef avatar jennyscript-ridecell avatar johanneslumpe avatar joshparolin avatar kyleamathews avatar leonaves avatar michaeljacobdavis avatar msonip avatar mukeshsoni avatar neaox avatar sa21 avatar wa-nadoo avatar yktv4 avatar yoihito 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-telephone-input's Issues

Don't warn if preferredCountries is an array of strings

   preferredCountries: React.PropTypes.arrayOf(React.PropTypes.object),

I get a warning due to the above line, but it looks like the rest of the code treats preferredCountries as an array of strings.

warning.js:46 Warning: Failed propType: Invalid prop preferredCountries[0] of type string supplied to ReactTelephoneInput, expected object

Less complains that flag.png is missing

I copied the flags.png file from the examples/src folder to the /less folder which solved things. Is this what it should be by default? I don't use Less so unsure.

Checking against hardcoded values in `getCountryDropDownList`

Not sure whether you really intended to do the following:

let itemClasses = classNames({
    country: true,
    preferred: country.iso2 === 'us' || country.iso2 === 'gb',
    active: country.iso2 === 'us',
    highlight: this.state.highlightCountryIndex === index
});

On first sight it does seem like that this is not supposed to be like this. Why should only the us and gb codes determine whether something is preferred?

when initialValue or Value is changed in the props

Hi Mukesh,

         When I am initializing component for the first time, I am passing a initialValue to the ReactTelephoneInput and it is populating. You are storing the value I am passing in the state after doing formatting in formattedNumber. Issue is when I changed initialValue after some time, then value stored inside state(which is old initialValue) is shown, but not the new initialValue

Can't choose countries with arrow-buttons

If I try to move in the list of countries using arrow-buttons , it doesn't work and console says: Uncaught TypeError: Cannot read property 'setState' of undefined

lessify is required

when I do npm install react-telephone-input on Node 4.0, and then try to use this component, I get

Cannot find module 'lessify' from '/…<snip>…/node_modules/react-telephone-input'

Exclude built files from repo

Having built files in the repo makes diffs sort of confusing. Have you considered adding those directories to gitignore?

The way I've seen other projects do it is to run a build in prepublish. That way when you publish, you'll be publishing the latest build but don't need it to be checked in.

Unusable because of React dependency

sorry to say but your component is unusable for me (although it looked promising) because it has a direct dependency on react instead of a peerDependency. This makes my app load react twice and it ends up with 'Only a ReactOwner can have refs' errors.

less-loader is required

When running my webpack configuration, the build is failing over this line:
require('../less/default.less');
Since I do not have less-loader in my project, it does not know how to handle .less files.

What do you think will be the right solution to this? precompile the css? have it as an external file to include in the project?

I am curious to so learn your opinion about that. Thanks! :D

Bug for Jamaican Numbers?

Hello,

Thanks the library. I think I got a small bug:

+1 876-211-1821

This is an American Number, but it looks like Jamaican... It should be like this?

How do you get value out of the module?

I've tried wrapping it in a form element, but onSubmit doesn't return any values. There don't seem to be any hooks for passing down a function to handle actions, how do you go about getting the value out?

Incorrect flag icons - source for flag icons potentially out of date

It looks like the source for the flag icons may be out of date - the Tuvalu Islands flag icon seems to be of their previous flag, which was superceded by the current flag in 1997.

I did not check each flag icon to see if it was correct : ) but finding at least one seemingly incorrect flag seems to me to indicate that other flags may be incorrect as well.

screen shot 2016-07-07 at 10 13 22 am

screen shot 2016-07-07 at 10 13 44 am

The Wallis and Futuna flag also seems to be their unofficial flag rather than their official flag, which seems to be the flag of France. Choosing one or the other of those options to represent Wallis and Futuna could be taking a political stance (I don't know, but seems worth considering):
screen shot 2016-07-07 at 10 29 36 am
screen shot 2016-07-07 at 10 29 25 am

Create a display-only version of the component.

It would be nice to have a way to display the formatted phone number for use in a non-edit view.

Would it be possible to export the formatting functionality or a component that would display the formatted number and (optional) country flag?

number flip

Hey,
when you mark the whole input (including the +) and starting to type a new number
the numbers in places 2 and 3 are jumping to the start of the input.

example: If i type 123
the expected is : +123
what actually happens : +231

Is there a fix for this unwanted behavior?
thanks

Can't load with webpack / babel setup

I have the current webpack setup:

module.exports = {
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    entry : './src/client.js',
    output: {
        path      : require('path').resolve('./build/js/'),
        publicPath: '/public/js/',
        filename  : '[name].js'
    },
    module: {
        loaders: [
            { test: /\.css$/, loader: 'style!css' },
            { test: /\.js$/, exclude: /node_modules/, loader: require.resolve('babel-loader') },
            { test: /\.json$/, loader: 'json-loader'},
            { test: /\.js$/, loader: 'eslint-loader', exclude: /node_modules/ },
            { test: /\.less$/, loader: 'style!css!less' }, // Added only to try to have support for LESS
        ]
    },
    stats: {
        colors: true
    },
    devtool  : 'source-map',
    watch    : true,
    keepalive: true,
    plugins  : [],
};

When I do import ReactTelInput from 'react-telephone-input'; it crashes with the following error:

[..]/node_modules/react-telephone-input/less/default.less:1
(function (exports, require, module, __filename, __dirname) { .react-tel-input
                                                              ^
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] ([..]/node_modules/babel/node_modules/babel-core/lib/babel/api/register/node.js:171: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.<anonymous> ([..]/node_modules/react-telephone-input/lib/index.js:28:1)
    at Module._compile (module.js:460:26)

Webpack / the Bable loader seem to try to include the .less file as a JS file. Is there a way of forcing it to be LESS?

Manually commenting the require('../less/default.less'); solves my issue for now as I can manually compile the LESS, but it obviously isn't ideal.

Selecting the current country when input is blank does not populate the country code

I just noticed that when a form is empty (either the user removes the input value, or it's a controlled component and initialValue is empty), selecting the current country does not add the country code.

Seems like if a user deletes all the content and then reselects the current country, for example 'United States', it should populate the input with +1.

Add a check here:

if((currentSelectedCountry.iso2 !== nextSelectedCountry.iso2) || this.state.formattedNumber === '+')

Use with Redux-Form

Hi, I am trying to use this with redux form (v6) and having some trouble with propagating errors back up to the form component. It appears that no name property is set on the inner input of this control. In redux-form we pass in a name and set it on the input.

My input is defined like this:

const telInput = props => {
  return <ReactTelephoneInput {...props.input} />
}

and instantiated like this:

 <Field
            classNames="editable-phone"
            component={telInput} name="phoneNumber" id="telInput" flagsImagePath="/images/flags.png"
            preferredCountries={['au', 'gb', 'us', 'nz']} defaultCountry={defaultCountry} />

When I reject the submission with Promise.reject, the error does not appear.

Unable to resolve module ../less/default.less

I did an npm install but when importing the module I get the following error:

"Unable to resolve module ../less/default.less from /Users/username/Dev/AwesomeProject/node_modules/react-telephone-input/lib/index.js: Invalid directory /Users/username/Dev/AwesomeProject/node_modules/react-telephone-input/less/default.less"

I checked and all the paths and files exist.

Enable support for autocomplete

Right now, the input field inside this component does not get autocompleted. One way to do it would be to add autoComplete='tel' as one of the attributes to the input tag

Features request

This is a fast and compact component but it's missing a few important features such as:

  • Can't tell from the callback if the number is valid or not, it just gives me a number.
  • No way to pass a number into it via props, the state is defaulted to ''
  • Would be nice to have a numbers only format without hyphens, spaces etc

How to get a name of the input

Hi,

I'm using ReactTelephoneInput.js like a child component. But I would like to validate two input fields with it. I have something like this :

screen shot 2016-07-12 at 15 58 36

And it works for mobilePhone field but I would like to implement it for phone field also. In my main component I have a function with which I set the state of my main component :

setNumber(telNumber, selectedCountry){
        let user = this.state.user;
        const nrFormat = selectedCountry.format;
        const givenNr = telNumber;

        user.mobilePhone = givenNr;


        if(nrFormat){
            if(givenNr.length == nrFormat.length){
                user.mobilePhoneFormat = true;
            }else{
                user.mobilePhoneFormat = false;
                user.mobilePhoneFormatCorrect = nrFormat;
            }
        }else{
            user.mobilePhoneFormat = true;
        }

        this.setState({user: user});

    }

Is there any way to do validation of phone field also inside this function?

And is there any way to add two formats for the same country. For example for Belgium there are mobile numbers in the format +32 ... .. .. .. and the phone numbers are in the format +32 . ... .. ..

Vertical offset is off when opening the country list

When I open the country list, the list should jump to the selected country based on the inputted country number, but the vertical offset is off as can be seen in the screenshot below. First I thought this was caused by some custom styling I added but I have removed all custom styling and the issue remains.

My code looks as follows:

<ReactTelInput
    defaultCountry={preferredCountries[0]}
    preferredCountries={preferredCountries}
    flagsImagePath='/static/assets/img/checkout/flags.png'
    onChange={(phoneNumber, country) => onChange(phoneNumber, country.name)}
    onBlur={(phoneNumber, country) => onChange(phoneNumber, country.name)}
    value={field.value}
/>

screen shot 2016-09-21 at 2 34 42 pm

Thanks in advance!

Feature Request: Add an `onFocus` handler to be passed as prop?

Hi,
At the moment, I have no way of knowing when the user has placed their cursor into the telephone input field. Adding an onFocus prop (to complement the already-implemented onBlur prop) would allow me to track when the user's cursor enters and leaves the input.

Would it be possible to do this?
I can probably submit a pull request to make this easier.
Regards,
Colm

Initial state w/ redux forms

Great component! however when using this in conjunction with redux-forms, I am unable to set initialValue of component (it is automatically changing input value to '+'). anyone else run into this problem?

How I can use it with requirejs?

Hi.
I use django, requirejs, gulp and bower in project.
So I try to load this module async like

define(['react-telephone-input'], function(TelInput){
  /* do something */
});

and I get an error Uncaught error: Module name .... include require([]);
I try wrap that in r.js -convert, but I get the same error by deps for this plugin.

Thanks for your attention.

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.