showing results for - "cascading dropdown for forms react"
Elana
17 Mar 2017
1import React from 'react';
2
3class Dropdown extends React.Component {
4	constructor(props) {
5		super(props);
6		this.state = {
7			countries : [],
8			states : [],
9			cities : [],
10			selectedCountry : '--Choose Country--',
11			selectedState : '--Choose State--'
12		};
13		this.changeCountry = this.changeCountry.bind(this);
14		this.changeState = this.changeState.bind(this);
15	}
16  
17	componentDidMount() {
18		this.setState({
19			countries : [
20				{ name: 'Germany', states: [ {name: 'A', cities: ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn']} ] },
21				{ name: 'Spain', states: [ {name: 'B', cities: ['Barcelona']} ] },
22				{ name: 'USA', states: [ {name: 'C', cities: ['Downers Grove']} ] },
23				{ name: 'Mexico', states: [ {name: 'D', cities: ['Puebla']} ] },
24				{ name: 'India', states: [ {name: 'E', cities: ['Delhi', 'Kolkata', 'Mumbai', 'Bangalore']} ] },
25			]
26		});
27	}
28  
29	changeCountry(event) {
30		this.setState({selectedCountry: event.target.value});
31		this.setState({states : this.state.countries.find(cntry => cntry.name === event.target.value).states});
32	}
33
34	changeState(event) {
35		this.setState({selectedState: event.target.value});
36		const stats = this.state.countries.find(cntry => cntry.name === this.state.selectedCountry).states;
37		this.setState({cities : stats.find(stat => stat.name === event.target.value).cities});
38	}
39	
40	render() {
41		return (
42			<div id="container">
43				<h2>Cascading or Dependent Dropdown using React</h2>
44	
45				<div>
46					<label>Country</label>
47					<select placeholder="Country" value={this.state.selectedCountry} onChange={this.changeCountry}>
48						<option>--Choose Country--</option>
49						{this.state.countries.map((e, key) => {
50							return <option key={key}>{e.name}</option>;
51						})}
52					</select>
53				</div>
54
55				<div>
56					<label>State</label>
57					<select placeholder="State" value={this.state.selectedState} onChange={this.changeState}>
58						<option>--Choose State--</option>
59						{this.state.states.map((e, key) => {
60							return <option key={key}>{e.name}</option>;
61						})}
62					</select>
63				</div>
64				
65				<div>
66					<label>City</label>
67					<select placeholder="City">
68						<option>--Choose City--</option>
69						{this.state.cities.map((e, key) => {
70							return <option key={key}>{e}</option>;
71						})}
72					</select>
73				</div>
74			</div>
75		)
76	}
77}
78
79export default Dropdown;