PL
React - lista rozwijana na podstawie tablicy
0 points
W tym artykule chcielibyśmy pokazać, jak stworzyć listę rozwijaną na podstawie tablicy w Reakcie.
Szybkie rozwiązanie:
xxxxxxxxxx
1
// Uwaga: Odkomentuj poniższe linijki podczas pracy z kompilatorem JSX:
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const colors = [
6
{value: 'czerwony', text: 'Czerwony'},
7
{value: 'żółty', text: 'Żółty'},
8
{value: 'niebieski', text: 'Niebieski'}
9
];
10
11
const App = () => {
12
const [color, setColor] = React.useState('red');
13
const handleChange = e => setColor(e.target.value);
14
const handleSubmit = e => {
15
e.preventDefault();
16
const data = {
17
color: color
18
};
19
const json = JSON.stringify(data);
20
console.clear();
21
console.log(json);
22
};
23
return (
24
<form onSubmit={handleSubmit}>
25
<div>
26
<label>
27
Wybierz swój ulubiony kolor:
28
<select value={color} onChange={handleChange}>
29
{colors.map(item => {
30
return (<option key={item.value} value={item.value}>{item.text}</option>);
31
})}
32
</select>
33
</label>
34
</div>
35
<button type='submit'>Zatwierdź</button>
36
</form>
37
);
38
};
39
40
const root = document.querySelector('#root');
41
ReactDOM.render(<App />, root);
W poniższym przykładzie przesyłamy tablicę opcji jako właściwość.
xxxxxxxxxx
1
// Uwaga: Odkomentuj poniższe linijki podczas pracy z kompilatorem JSX:
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const Select = ({value, options, onChange}) => {
6
return (
7
<select value={value} onChange={onChange}>
8
{options.map(option => {
9
return (<option key={option.value} value={option.value}>{option.text}</option>);
10
})}
11
</select>
12
);
13
};
14
15
const colors = [
16
{value: 'czerwony', text: 'Czerwony'},
17
{value: 'żółty', text: 'Żółty'},
18
{value: 'niebieski', text: 'Niebieski'}
19
];
20
21
const App = () => {
22
const [color, setColor] = React.useState('red');
23
const handleChange = e => setColor(e.target.value);
24
const handleSubmit = e => {
25
e.preventDefault();
26
const data = {
27
color: color
28
};
29
const json = JSON.stringify(data);
30
console.clear();
31
console.log(json);
32
};
33
return (
34
<form onSubmit={handleSubmit}>
35
<div>
36
<label>
37
<span>Wybierz swój ulubiony kolor:</span>
38
<Select value={color} options={colors} onChange={handleChange} />
39
</label>
40
</div>
41
<button type='submit'>Submit</button>
42
</form>
43
);
44
};
45
46
const root = document.querySelector('#root');
47
ReactDOM.render(<App />, root);