-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
95 lines (81 loc) · 2.03 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import React, { useState } from "react";
import ReactDOM from "react-dom";
function List(props) {
const { name, items, value, handler } = props;
const options = [];
options.push(
<option key={name} value={name}>
{name}
</option>
);
for (var index in items) {
const item = items[index];
options.push(
<option key={item} value={item}>
{item}
</option>
);
}
return (
<select value={value || name} onChange={handler}>
{options}
</select>
);
}
function TwoLists(props) {
const [brand, changeBrand] = useState(null);
const [model, changeModel] = useState(null);
const brands = () => Object.keys(props.data);
const models = () =>
brand !== null ? props.data[brand] : [];
const knownBrand = brand => brands().indexOf(brand) !== -1;
const knownModel = model => models().indexOf(model) !== -1;
const brandChanged = event => {
const brand = event.target.value;
if (knownBrand(brand)) {
changeBrand(brand);
} else {
changeBrand(null);
}
changeModel(null);
}
const modelChanged = event => {
const model = event.target.value;
if (knownModel(model)) {
changeModel(model);
} else {
changeModel(null);
}
}
const buttonClicked = event => {
console.log(`${brand} ${model} riding...`);
}
const buttonDisabled = () => brand === null || model == null;
return (
<div id={props.id}>
<List
name="Brand"
items={brands()}
value={brand}
handler={brandChanged}
/>
<List
name="Model"
items={models()}
value={model}
handler={modelChanged}
/>
<button onClick={buttonClicked} disabled={buttonDisabled()}>
Ride
</button>
</div>
);
}
TwoLists.defaultProps = {
data: {
Opel: ["Agila", "Astra", "Corsa", "Vectra"],
Skoda: ["Fabia", "Octavia", "Superb", "Yeti"],
Toyota: ["Auris", "Avensis", "Corolla", "Prius"]
}
};
ReactDOM.render(<TwoLists id="two-lists" />, document.getElementById("root"));