Atributi value selecta iz tabele v Reactu
Naj naši elementi seznama spet shranijo v tabeli:
function App() {
const texts = ['text1', 'text2', 'text3', 'text4'];
const [value, setValue] = useState('');
...
}
Z uporabo te tabele oblikujmo
oznake option in jim dodajmo kot atribute
value vrednosti elementov tabele:
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>;
});
...
}
Z uporabo oblikovanih oznak ustvarimo spustni seznam:
return <div>
<select value={value} onChange={event => setValue(event.target.value)}>
{options}
</select>
</div>;
V odstavek izpišimo številko izbranega elementa:
return <div>
<select value={value} onChange={event => setValue(event.target.value)}>
{options}
</select>
<p>
vaša izbira: {value}
</p>
</div>;
Zdaj pa izpišimo besedilo izbranega elementa, z uporabo njegove številke in tabele z besedili:
return <div>
<select value={value} onChange={event => setValue(event.target.value)}>
{options}
</select>
<p>
vaša izbira: {texts[value]}
</p>
</div>;
Vse skupaj sestavimo in dobimo naslednjo kodo:
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ša izbira: {texts[value]}
</p>
</div>;
}