React.js ライブラリ「react-country-region-selector」を使用して国や地域をセレクトボックスに表示する

React.js ライブラリ「react-country-region-selector」を使用して国や地域をセレクトボックスに表示する

ライブラリ「react-country-region-selector」をインストールすると、国や地域をセレクトボックスに表示すること可能です。ここでは、react.jsで react-country-region-selector を利用するための手順と簡単な使い方を記述してます。

環境

  • OS  CentOS Linux release 8.0.1905 (Core)
  • node V12.13.1
  • npm 6.14.4
  • React 16.13.0

react.js環境構築

下記のコマンドで構築してます。ここでは、react-appという名前でプロジェクトを作成してます。

create-react-app react-app

react-country-region-selectorインストール

作成したプロジェクトに移動して、インストールします。

## 作成したプロジェクトに移動
cd react-app
 
## インストール
npm install react-country-region-selector

react-country-region-selector使い方

srcディレクトリにsample.jsと名前で下記のコードを記述します。

import React, { Component } from 'react';
import { CountryDropdown, RegionDropdown, CountryRegionData } from 'react-country-region-selector';

class Sample extends Component {
    constructor (props) {
      super(props);
      this.state = { country: '', region: '' };
    }
  
    selectCountry (val) {
      this.setState({ country: val });
    }
  
    selectRegion (val) {
      this.setState({ region: val });
    }
  
    render () {
      const { country, region } = this.state;
      return (
        <div>
          <CountryDropdown
            value={country}
            onChange={(val) => this.selectCountry(val)} />
          <RegionDropdown
            country={country}
            value={region}
            onChange={(val) => this.selectRegion(val)} />
        </div>
      );
    }
  }

export default Sample

次に、srcディレクトリ配下にあるApp.jsを下記のように編集します。

import React from 'react';
import Sample from './sample';
import './App.css';

function App() {
  const style = {
    width: "50%",
    margin: "0 auto",
    marginTop: 150,
  };
  return (
    <div className="App">
      <div style={style}>
        <Sample />
      </div>
    </div>
  );
}

export default App;

実行します。

npm start

ブラウザから http://プライベートIP:3000にアクセスすると、国や地域がセレクトボックスで表示されていることが確認できます。