Atrybuty value select z tablicy w React

Załóżmy, że elementy listy ponownie przechowywane są w tablicy:

jsxfunction App() {
  const texts = ['text1', 'text2', 'text3', 'text4'];
  const [value, setValue] = useState('');
  
  ...
}

Utwórzmy za pomocą tej tablicy znaczniki option, dodając im jako atrybuty value wartości elementów tablicy:

jsxfunction 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>;
  });
  
  ...
}

Korzystając z utworzonych znaczników, stwórzmy rozwijaną listę:

jsxreturn <div>
  <select value={value} onChange={event => setValue(event.target.value)}>
    {options}
  </select>
</div>;

Wypiszmy w akapicie numer wybranego elementu:

jsxreturn <div>
  <select value={value} onChange={event => setValue(event.target.value)}>
    {options}
  </select>
  <p>
    Twój wybór: {value}
  </p>
</div>;

A teraz wypiszmy tekst wybranego elementu, korzystając z jego numeru i tablicy z tekstami:

jsxreturn <div>
  <select value={value} onChange={event => setValue(event.target.value)}>
    {options}
  </select>
  <p>
    Twój wybór: {texts[value]}
  </p>
</div>;

Połączmy wszystko razem i otrzymamy następujący kod:

jsxfunction 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>
      Twój wybór: {texts[value]}
    </p>
  </div>;
}