Elementy select z tablicy w React
Załóżmy, że mamy tablicę z tekstami elementów listy rozwijanej:
function App() {
const texts = ['text1', 'text2', 'text3', 'text4'];
const [value, setValue] = useState('');
return <div>
...
</div>;
}
Utwórzmy nasze znaczniki option w pętli:
function App() {
const texts = ['text1', 'text2', 'text3', 'text4'];
const [value, setValue] = useState('');
const options = texts.map((text, index) => {
return <option key={index}>{text}</option>;
});
return <div>
<select value={value} onChange={(event) => setValue(event.target.value)}>
{options}
</select>
<p>
Twój wybór: {value}
</p>
</div>;
}
Załóżmy, że w tablicy przechowywana jest lista miast. Wyświetl za pomocą pętli rozwijaną listę tych miast.