Elementi di selezione da un array in React
Supponiamo di avere un array con i testi degli elementi di un menu a tendina:
function App() {
const texts = ['text1', 'text2', 'text3', 'text4'];
const [value, setValue] = useState('');
return <div>
...
</div>;
}
Creiamo i nostri tag option in un ciclo:
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>
la tua scelta: {value}
</p>
</div>;
}
Supponiamo che un array contenga un elenco di città. Visualizza un menu a tendina di queste città utilizzando un ciclo.