Vrednosni atributi select-a iz niza u React-u
Neka su nam opet stavke liste sačuvane u nizu:
function App() {
const texts = ['text1', 'text2', 'text3', 'text4'];
const [value, setValue] = useState('');
...
}
Hajde da formiramo pomoću ovog niza
tagove option, dodajući im kao atribute
value vrednosti elemenata niza:
function App() {
const texts = ['text1', 'text2', 'text3', 'text4'];
const [value, setValue] = useState('');
const options = texts.map((text, index) => {
return <option key={index} value={index}>{text}</option>;
});
...
}
Koristeći formirane tagove kreirajmo padajući spisak:
return <div>
<select value={value} onChange={event => setValue(event.target.value)}>
{options}
</select>
</div>;
Ispišimo u pasus broj izabrane stavke:
return <div>
<select value={value} onChange={event => setValue(event.target.value)}>
{options}
</select>
<p>
vaš izbor: {value}
</p>
</div>;
A sada ispišimo tekst izabrane stavke, koristeći njegov broj i niz sa tekstovima:
return <div>
<select value={value} onChange={event => setValue(event.target.value)}>
{options}
</select>
<p>
vaš izbor: {texts[value]}
</p>
</div>;
Sakupimo sve zajedno i dobijamo sledeći kod:
function App() {
const texts = ['text1', 'text2', 'text3', 'text4'];
const [value, setValue] = useState('');
const options = texts.map((text, index) => {
return <option key={index} value={index}>{text}</option>;
});
return <div>
<select value={value} onChange={event => setValue(event.target.value)}>
{options}
</select>
<p>
vaš izbor: {texts[value]}
</p>
</div>;
}