⊗jsrtPmFmsAV 67 of 112 menu

Select Value Attributes from Array in React

Let's again store the list items in an array:

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

Let's use this array to form option tags, adding the values ​​of the array elements as value attributes:

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

Using the generated tags, we will create a drop-down list:

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

Let's display the number of the selected item in the paragraph:

return <div> <select value={value} onChange={event => setValue(event.target.value)}> {options} </select> <p> your choice: {value} </p> </div>;

Now let's display the text of the selected item using its number and an array of texts:

return <div> <select value={value} onChange={event => setValue(event.target.value)}> {options} </select> <p> your choice: {texts[value]} </p> </div>;

Let's put it all together and get the following code:

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> your choice: {texts[value]} </p> </div>; }
enru