Giter Club home page Giter Club logo

react-country-region-selector's Introduction

react-country-region-selector

Build Status


About

This library provides a pair of React components to display connected country and region dropdowns (pick a country, it shows the relevant regions). If you're not using React, check out the plain vanilla JS version instead. The list of countries and regions is maintained separately and found in the country-region-data repo.

Features

It's pretty versatile.

  • There are two separate components (<CountryDropdown />, <RegionDropdown>) that you can embed in your DOM wherever you need. That sounded like a vulgar euphemism, but it wasn't, honest.
  • The source data used by the library is also exposed, should you need it.
  • It let's you customize the list of countries that appears via a whitelist, blacklist.
  • A lot of options are provided, for things like styling, event callbacks and so on.
  • To keep file sizes down you have the option of creating a custom build of the library containing only a list of those countries you want to show up. See command line options for more info.

Gotchas

  • Page charset: some country names contain UTF-8 chars, so your page will need an appropriate charset to handle them. If you see some invalid characters appearing in the dropdown, make sure you have UTF-8 specified in your page <head>, like so: <meta charset="UTF-8">
  • Return values: on an onChange event event.target.value is returned as the first value and the full event as the second.

Demo

Check out the github pages section for some examples + example JSX code.

Installation

Using npm or yarn:

npm i react-country-region-selector
yarn add react-country-region-selector

Usage

It's very easy to use, but note that you will need to track the country and region value somewhere - either in your component state or in a store somewhere. Here's a simple example that uses state:

import React, { useState } from 'react';

// note that you can also export the source data via CountryRegionData. It's in a deliberately concise format to 
// keep file size down
import { CountryDropdown, RegionDropdown, CountryRegionData } from 'react-country-region-selector';


const Example = () => {
  const [country, setCountry] = useState('');
  const [region, setRegion] = useState('');

  return (
    <div>
      <CountryDropdown
        value={country}
        onChange={(val) => setCountry(val)} />
      <RegionDropdown
        country={country}
        value={region}
        onChange={(val) => setRegion(val)} />
    </div>
  );
}

Generally you don't need CountryRegionData, but if you should need it, the raw data is accessible like in the above example.

Options

These are the attributes that can be passed to the two components. Note: any other attributes that aren't specified here will be added directly to the <select> DOM element.

<CountryDropdown />

Parameter Required? Default Type Description
value Yes "" string The currently selected country. This should either be the shortcode, or the full country name depending on what you're using for your value attribute (see the valueType option). By default it's the full country name.
onChange Yes - function Callback that gets called when the user selects a country. Use this to store the value in whatever store you're using (or just the parent component state).
onBlur No - function Callback that gets called when the user blurs off the country field.
name No "rcrs-country" string The name attribute of the generated select box.
id No "" string The ID of the generated select box. Not added by default.
classes No "" string Any additional space-separated classes you want to add.
showDefaultOption No true boolean Whether you want to show a default option.
priorityOptions No array [] Lets you target countries that should appear at the top of the dropdown. Should also be an array of country shortcodes.
defaultOptionLabel No "Select Country" string The default option label.
labelType No "full" string Either "full" or "short". This governs whether you see country names or country short codes in the dropdown.
valueType No "full" string Either "full" or "short". This controls the actual value attribute of each <option> in the dropdown. Please note, if you set this to "short" you will need to let the corresponding <RegionDropdown /> component know as well, by passing a countryValueType="short" attribute.
whitelist No [] array This setting lets you target specific countries to appear in the dropdown. Only those specified here will appear. This should be an array of country shortcodes. See the country-region-data repo for the data and the shortcodes.
blacklist No [] array Lets you target countries that should not appear in the dropdown. Should also be an array of country shortcodes.
disabled No false boolean Disables the country field.

<RegionDropdown />

Parameter Required? Default Type Description
country Yes "" string The currently selected country.
value Yes "" string The currently selected region.
onChange Yes - function Callback that gets called when the user selects a region. Use this to store the value in whatever store you're using (or just the parent component state).
onBlur No - function Callback that gets called when the user blurs off the region field.
name No "rcrs-region" string The name attribute of the generated select box.
id No "" string The ID of the generated select box. Not added by default.
classes No "" string Any additional space-separated classes you want to add.
blankOptionLabel No - string The label that appears in the region dropdown when the user hasn't selected a country yet.
showDefaultOption No true boolean Whether you want to show a default option. This is what the user sees in the region dropdown after selecting a country. It defaults to the defaultOptionLabel setting (see next).
defaultOptionLabel No Select Region string The default region option.
onChange No - function Called when the user selects a region. Use this to store the region value.
countryValueType No full string If you've changed the country dropdown valueType to short you will need to set this value to short as well, so the component knows what's being passed in the country property.
labelType No "full" string Either "full" or "short". This governs whether you see region names or region short codes in the dropdown.
valueType No "full" string Either "full" or "short". This controls the actual value attribute of each <option> in the dropdown.
disableWhenEmpty No false boolean Disables the region field when the user hasn't selected a country.
disabled No false boolean Disables the region field. If set to true, it overrides disableWhenEmpty
customOptions No [] Array<string> Appends a list of string to the every region dropdown, regardless of the country selected.
whitelist No { CountryCode: [] } object This setting lets you target specific regions to appear in the dropdown. Only those specified here will appear. This should be an array of region codes keyed by the country code.
blacklist No { CountryCode: [] } object This setting lets you target specific regions that should not appear in the dropdown. This should be an array of region codes keyed by the country code.
disabled No false boolean Disables the region field. If set to true, it overrides disableWhenEmpty

Command-line

Check out the scripts section of the package.json file to see them all, but these are the highlights:

  • npm start - regenerate everything, plus a watcher for local development.
  • npm build - build the dist files again. No watcher.
  • rollup -c --config-countries=UK,US - generate a custom build of the script /dist folder containing only those countries you specify here. This seriously reduces file size, so if you can do it, do it.

Changelog

  • 3.6.1 - Aug 3, 2022
    • Dependency version fix.
  • 3.6.0 - Aug 2, 2022
    • React 18 support added.
  • 3.5.0 - Jul 30, 2022
    • Upgrade country-region-data to 2.6.0.
  • 3.4.0 - Oct 24, 2021
    • Typings fix.
    • Upgrade country-region-data to 1.11.0.
  • 3.3.0 - Aug 17, 2021
    • Upgrade country-region-data to 1.10.0.
  • 3.2.0 - Jul 30, 2021
    • Upgrade country-region-data to 1.9.0.
  • 3.1.0 - May 11, 2021
    • React 17 support added, thanks madhums!
  • 3.0.2 - Jan 18, 2021
    • typings file fix.
  • 3.0.1 - Sep 26, 2020
    • typings file fix.
  • 3.0.0 - Sep 8, 2020
    • blacklist option added for the Region component (thanks Mitch Rickman!)
    • typings fix and onBlur callback standardized with value passed as first param, with full event as second. This is a breaking change. Thanks Vinod Ramakrishnan!
  • 2.1.0 - Mar 28, 2020
    • country-region-data updated to 1.6.0
  • 2.0.0 - Mar 21, 2020
    • Typings fixes
    • Dependency updates
  • 1.4.7 - Dec 24, 2019:
    • Fix to include typings in published bundle.
  • 1.4.6 - Dec 22, 2019:
  • 1.4.5 - Oct 9, 2019.
    • country region data updated to 1.5.0
    • RegionDropdown component updates to refactor deprecated componentWillReceiveProps method
    • misc dependency updates
  • 1.4.4 - Aug 2, 2019. Country data updates.
  • 1.4.3 - Dev 2, 2018:
    • RegionDropdown converted to PureComponent; now updates on any prop change
    • country region data updated to 1.4.5
  • 1.4.2 - Nov 8, 2018:
    • customOptions setting added for the Region dropdown.
    • priorityOptions option added to the CountryDropdown to allow placing items at the top of the country dropdown.
  • 1.4.1 - Sept 9, 2018: bug fix for invalid JSON data source conversion.
  • 1.4.0 - Sept 8, 2018:
    • Breaking change: the library is no longer exported in UMD format. Now it's only exported in es6 (dist/rcrs.es.js) and commonJS (dist/rcrs.js) format. This library is intended for use in React applications.
    • Breaking change: no longer available via Bower. I don't recall ANY react component used via Bower, so if I'm mistaken here, open a github issue to explain your use-case and I can re-add it.
      If you need UMD, check out the plain vanilla version.
    • country-region-data updated to latest version (1.4.4)
    • You can now pass arbitrary attributes to the components (e.g. style={{ color: 'red' }} and have them output in the markup)
    • the old gulp build process updated to use rollup
    • this component library, the source data set and the plain vanilla JS version are now all grouped under a single github organization
  • 1.3.0 - Mar 20, 2018. Bug fix for invalid country, @n-david! onBlur event added.
  • 1.2.3 - Nov 7, 2017. Country data updates. React moved to peer dependency, thanks @iamdey!
  • 1.2.2 - Oct 4, 2017 - Update to pass event on change. Thanks @robertnealan!
  • 1.2.1 - Sept 6, 2017 - IE11 bug fix.
  • 1.2.0 - Aug 7, 2017 - updated country-region-data; dependency updates.
  • 1.1.0 - May 18, 2017 - dependency updates. disabled option added to <CountryDropdown /> and <RegionDropdown />.
  • 1.0.4 - April 12, 2017 - bug fix. Thanks @bebbi and @tchaffee!
  • 1.0.3 - Jan 2, 2016 - updated country-region-data, repo link fix.
  • 1.0.2 - October 16, 2016 - Fix issue where source-data.js in lib had no country data.
  • 1.0.0 - July 1, 2016 - initial version.

Tests

The Jest/Enzyme unit tests are found in the src/tests folder. The repo is hooked up to Travis CI to automatically run the tests for each commit.

Local Dev

This is pretty dated, I'm afraid. But to run this locally, do the following:

  • npm install
  • in one terminal window: npm start
  • in another terminal window, go to the /example subfolder and do the same: npm install, npm start
  • open http://localhost:3000 in your browser.

Thanks!

Big thanks to a whole boatload of people:

  • contributors to this project and the source data.
  • Special thanks to the create-react-library tool which I use here (un-ejected) to rollup this component library. Great stuff.

License

MIT.

react-country-region-selector's People

Contributors

acethecreator avatar asplogic avatar bebbi avatar benkeen avatar canrau avatar dependabot[bot] avatar iamclaytonray avatar iamdey avatar jamesjessian avatar jan-rodriguez avatar jshenk avatar kevinrademan avatar ksnyder avatar kyledavisdev avatar madhums avatar mitch-rickman avatar n-david avatar samya-ak avatar shishiranshuman avatar simonschick avatar skene avatar steven-r avatar thetimbanks avatar vinod-rp 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

react-country-region-selector's Issues

Per-country feature to use short values for regions

I think it would be great to add some props to the RegionDropdown where a list of countries could be specified that override the labelType and valueType props only for those countries.

For example, you could have something like valueTypeCountriesShort={['US']} as well as labelTypeCountriesShort={['US']} to make only the United States show regions using short codes even if the overall setting for valueType and labelType is "full". I don't really know if any other countries use short codes for addresses, but in America it is standard to use short codes for the states, so it would be helpful to have the option of using short codes for American states but full values for all other country regions.

Ability to make readOnly

Is there any way to make the select field readOnly? I can't use disabled because I need a selected value submitted. I have a case where what I really need is to make option selection change not available to an end-user, so that the app will select it automatically based on a different decision elsewhere in the form.

How to properly select Default values

Hi there,

I've been using react-country-region-selector in my project, but I'm having trouble figuring out how to properly make an "update" page.

By specs we are not allowed to specify defaultValue, so I was wondering if at the moment this isn't supported. I'd also need to specify a defaultCountry in the region selector.

At the moment I'm using defaultOptionLabel and blankOptionLabel but this breaks the form as the country isn't really selected, only its name is shown.
Same goes for the region selector, which instead is completely broken as the dropdown to change region only works after changing the country.

I'm wondering if I'm using the library in the wrong way or if this is not supported and you'd accept a PR that adds these features.

Here's my current code at the moment for reference πŸ‘‡

<fieldset disabled={loading} aria-busy={loading}>
                    <label htmlFor="country">
                      Country
                      <CountryDropdown
                        defaultValue={data.user.country}
                        name="country"
                        id="country"
                        value={this.state.country}
                        onChange={val => this.selectCountry(val)}
                        defaultOptionLabel={data.user.country}
                      />
                    </label>
                  </fieldset>
                  <fieldset disabled={loading} aria-busy={loading}>
                    <label htmlFor="region">
                      Region
                      <RegionDropdown
                        defaultValue={data.user.region}
                        name="region"
                        id="region"
                        country={this.state.country}
                        value={this.state.region}
                        onChange={val => this.selectRegion(val)}
                        blankOptionLabel={data.user.region}
                        defaultOptionLabel={data.user.region}
                      />
                    </label>
                  </fieldset>

Ability to add list of popular/common countries to top

I believe this is a feature request for functionality not currently supported, but please correct me if I'm mistaken.

I would like to be able to list a set of countries that would appear at the top of the list, separated by a vertical line from the overall alphabetical list. The top list would include the countries that are the most common choices of my users.

For example:

United States
Canada


Afghanistan
Aland Islands
...

The common countries would then be repeated in the list below. I don't believe I can accomplish this with whitelist and blacklist, but let me know if that's a wrong assumption.

Hot to edit label in css?

How to edit the css? I can only edit the general selector style, not other stuff like the arrow, the label, the color of the text after an inserction..

Minor doc issues

In examples, wrong param region={} for RegionDropdown.
In README, countryValue => country.

onChange returns event.target.value rather than full event

In many instances I often set a shared onChange handler to all inputs in a form, that trigger a common setState function that updates the state based on the input name (this seems to be a common pattern as documented by the (https://facebook.github.io/react/docs/forms.html#handling-multiple-inputs)[React Forms Multiple Components section]). Unfortunately it looks like the actual built-in onChange handler only returns the e.target.value on lines 48 and 169 rather than the full event, breaking this pattern.

Suggesting an update to return the full event as shown in this commit of my fork (doesn't include the re-built files in this commit): https://github.com/SellingPower/react-country-region-selector/commit/47e5e5893f4b12adbe6e41d0a692cef1b2ba3b5b

Happy to put in a PR if this is of interest to you.

Fix demo page

Meh. Can't get the script to update github pages for 1.4.2. Fix!

Strange dependency: highlight.js

Hi,

First of all, great lib, thank you!
Secondly, I don't understand what for this library has highlight.js dependency?

Regards,
Jakub.

Utility for conversting countries and state/provinces to different alphas

Would it be possible to take a country and/or state/province that I already have that uses the full names and convert that with this package to the alpha-2 / short value? I want to use the short values in the dropdowns, so I need a way to convert my given address to the short value I can pass to the component. Thoughts?

*** Announcement: 1.4.1 released - includes breaking changes ***

Hey all, I just released 1.4.1. Please let me know if you run into any problems.

Release notes:

  • Breaking change: the library is no longer exported in UMD format. Now only exported in es6 (dist/rcrs.es.js) and commonJS (dist/rcrs.js) format. This library is intended for use in React applications.
  • Breaking change: no longer available via Bower. I don't recall ever including a react component used via Bower, so if I'm mistaken here, open a github issue to explain your use-case and I can re-add it. If you need UMD, check out the plain vanilla version.
  • country-region-data updated to latest version (1.4.4)
  • You can now pass arbitrary attributes to the components (e.g. style={{ color: 'red' }} and have them output in the markup)
  • the old gulp build process updated to use rollup.
  • this component library, the source data set and the plain vanilla JS version are now all grouped under a single github organization.

Demo here: http://country-regions.github.io/react-country-region-selector/

TypeScript support

As you know we've been using this library and it's working pretty well, we created some typings for internal use and would like you to publish them with your packages so others can use them too:

Contra:

  • Are you down to ship and maintain them?
  • They are not exactly complete You might want to check this
  • You re-export country-region-data which has no typings, I had to include them.
    • You might want to consider removing this export actually, if people want access to that list, tell them to import it from the package instead.
  • You broke the onChange interface contract (probably not intentionally), by calling onChange with the value of the input as first arg, which prevents me from extending InputHTMLAttributes.

Pro:

  • You would make development with your library about 5x easier for anyone using TS.
  • You get additional documentation for free
declare module 'react-country-region-selector' {
  import { InputHTMLAttributes } from 'react';

  interface Region {
    name: string;
    shortCode: string;
  }

  interface Country {
    countryName: string;
    countryShortCode: string;
    regions: Region[];
  }

  interface ReactCountryDropdownProps extends InputHTMLAttributes<string> {
    value: string;
    classes?: string;
    showDefaultOption?: boolean;
    defaultOptionLabel?: string | number;
    labelType?: number;
    valueType?: 'short' | 'full';
    whitelist?: string[];
    blacklist?: string[];
  }

  interface ReactRegionDropdownProps extends InputHTMLAttributes<string> {
    country: string;
    value: string | number;
    classes?: string;
    showDefaultOption?: boolean;
    defaultOptionLabel?: string | number;
    labelType?: number;
    countryValueType?: 'short' | 'full';
    whitelist?: string[];
    blacklist?: string[];
    disableWhenEmpty?: boolean;
  }

  class CountryDropdown extends React.Component<ReactCountryDropdownProps> {}
  class RegionDropdown extends React.Component<ReactRegionDropdownProps> {}

  const CountryRegionData: Country[];

  export { CountryDropdown, RegionDropdown, CountryRegionData };
}

1.4 checklist

Stuff to do before releasing 1.4:

  • Fix build process for building custom build with specific countries.
  • Pass-through attributes!
  • Rename index.js and index.es.js to rcrs.js and rcrs.es.js respectively.
  • Error in examples: "Warning: React does not recognize the showDefaultOption prop on a DOM element. "
  • Update README with 1.4 changes.

Cannot find module './source-data.js'

Cannot find module './source-data.js' from '/Users/Shrihari/projects/Sodastream-UI/node_modules/react-country-region-selector/dist'

My gulp throwing this error

The event passed on the onChange doesn't have the values for 'accessKey', 'name', etc

Hi,

This is related to the issue 'onChange returns event.target.value rather than full event #22' which is closed recently. I took the latest version and I'm able to get the event on onChange(). But the event.target doesn't contain the default values like: accessKey, name, etc.
I'm creating multiple RegionDropdown s dynamically.
Here is my method:
<RegionDropdown
accessKey={i}
name={stateSelect}

onChange={(val) => this.selectRegion(val, event)}
selectRegionΒ (value, target) {
console.log("Event-> ", event);

Console:
Event {isTrusted: false, type: "react-change", target: react, currentTarget: react, eventPhase: 2, …}
bubbles:false
cancelBubble:false
cancelable:false
composed:false
currentTarget:react
defaultPrevented:false
eventPhase:2
isTrusted:false
path:[react]
returnValue:true
srcElement:react
target:react
timeStamp:192776.21000000002
type:"react-change"
proto:Event

Target Object:
target:react
accessKey:""
assignedSlot:null
attributes:NamedNodeMap {length: 0}
baseURI:"http://localhost:3000/myApp"
childElementCount:0
childNodes:[]
children:[]
classList:[value: ""]
className:""

Thanks in Advance,
Sandy

Region selector not working in IE

Hi,

I noticed that any page that has the region selector included is not rendering properly in IE 11 and will break the page. The react country selector demos at http://benkeen.github.io/react-country-region-selector/ are breaking in IE 11 too.

On the website I am developing I am getting the following error in the IE console:

Unable to get property 'nextSibling' of undefined or null reference

Any ideas on how I can work around this?

Thank You!

Howdy, just wanted to say thanksβ€”this library was exactly what I needed, and so well written to be composable and easy to apply my own styles. Dropped it into my project and everything worked instantly! πŸ‘

Functionality to add more options to the dropdown.

Hello, I need to know if one of the following is possible or not:

  • Add our own custom options to the dropdown list.
  • Get the region list based on the country selected. If this is possible I can push the custom options to the region list and then render it inside the select tag.

For example: I need to add National in the region dropdown:
custom region-value

I could not find anything related to my above problem in the docs.

Thanks

Option not selected when value is present.

I have this package (which has been great outside of this one quirk - thank you) implemented, and it's not displaying a selected option when a value is passed into the component.

<CountryDropdown
    valueType="short"
    whitelist={Constants.countriesList}
    value={this.state.country}
    onChange={(val) => this.selectCountry(val)}
/>

In the above example, I have confirmed that this.state.country is equal to "US", and the select has an option with a value of "US" after setting valueType="short".

The RegionDropdown correctly shows a list of US states, but has the same issue as the CountryDropdown in that it displays the default 'Select Region' value as opposed to showing a selected state option.

Note (for clarity) that everything works fine when selecting new/different options - I'm only talking about displaying the proper selected option when the page loads, which is a common use-case when editing data.

border radius

I'm trying to remove the border-radius of the dropdown but I can't seem to do it.
I'm trying border-radius: unset and it overrides the default 5px but the component doesn't change

React as peerDependency?

I'm trying to upgrade to React v16 and I'm running into the issue described here:
https://stackoverflow.com/questions/46466253/migration-to-react-16-0-0-error-cannot-find-module-react-lib-reactcomponenttre

I get the output below when I run yarn list react and yarn list react-dom respectively:

$ yarn list react
yarn list v1.2.1
warning Filtering by arguments is deprecated. Please use the pattern option instead.
β”œβ”€ [email protected]
β”‚  └─ [email protected]
└─ [email protected]
✨  Done in 1.08s.
$ yarn list react-dom
yarn list v1.2.1
warning Filtering by arguments is deprecated. Please use the pattern option instead.
β”œβ”€ [email protected]
β”‚  └─ [email protected]
└─ [email protected]
✨  Done in 1.12s.

Should react-country-region-selector be specifying react as a peerDependency?

make blacklist work with full names if that is the valuetype selected

I am using the selector to populate a list of countries. the user should be able to pick each country once and only once. I was going to use the blacklist to facilitate this, but ran into a problem;

right now, if I want to use full names in my data store, but want to blacklist selected values I need to somehow retrieve the short name based on the full name from the raw data.

It seems logical that if I am using the full names, the blacklist should operate from the full name as well.

Missing Gulpfile

Hey guys, how do you build? There's no build command inside the package.json and no gulpfile as specified by the README.

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.