Search code examples
reactjsapidropdown

Fill Dropdown with Fetched API Items


I've build an react app where I am fetching all the repositories from a user. I am trying to fill a dropdown with the returned items, but it does not work. I only get it to make a dropdown for every repository.

if (!repos || repos.length === 0) return <p>No repos, sorry</p>;
    return (
        <ul>
            <h2 className='list-head'>Available Public Repositories</h2>
            {repos.map((repo) => {
                return (
                        <select>
                        <option>{repo.name}</option>
                        <select/>

                );
            })}
        </ul>

How do I fill a dropdown with the returned data?


Solution

  • It is because you have the <select> tag inside the map function. It is returning each element with a <select> tag.
    Therefore all you need to do this take the select tags out of the map.

    I also added a key and value for <option>. You can have it according to what you have in your repos data

            <ul>
                <h2 className='list-head'>Available Public Repositories</h2>
                 <select>
                    {repos.map((repo) => {
                      return (<option key={repo.repoId} value={repo.name}>{repo.name}</option> );
                    })}
                 <select/>       
            </ul>