Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically create options from a dropdown select menu in react

So, I’m trying to dynamically create the options of a select dropdown, I make the fetch of an api with the states of my country, but I don’t know how to access the content inside each object..

As you can see below, the data is being pulled from the API, that is, the fetch worked, but I don’t know how to create the options that will be inside the Select with each object..
d

import { EmailIcon, LocationIcon } from './assets/FormSvgIcons'
import { useEffect, useState } from 'react';

const SettingsForm = () => {
 const [stateList, setStateList] = useState([]);
 const [userLocation, setUserLocation] = useState('');

 const handleLocation = () => {
    setUserLocation(e.target.value);
 }

 useEffect(() => {
    let initialStates = [];

    fetch('https://servicodados.ibge.gov.br/api/v1/localidades/estados/')
        .then(response => {
            return response.json();
        }).then(data => {
            initialStates = data.map((states) => {
                return states
            });
            console.log(initialStates);
            setStateList({states: initialStates});
        });
 }, []);

 const createDropdownOptions = () => {
    const createOptions = stateList.map((state, i) => {
        Object.keys(state).map(singleState => (
            <option value={i}>{singleState.sigla}</option>
        ))
    });
    return createOptions;
 }

 return (
 <form>
    <div className="user-country">
            <label className="white-label">
                Local
            </label>
            <div className="input-icon-wrapper">
                <div className="icon-input w-embed">
                    <LocationIcon />
                </div>
                <select 
                    className="select-field white-select w-select"
                    id="locationField"
                    name="locationField"
                    onChange={handleLocation}
                >
                    {createDropdownOptions()}
                </select>
            </div>
        </div>
 </form>
 )

I know that the error is in the "createDropdownOptions" function because it is responsible for creating the options, but I don’t know how to do it, any light?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I see your problem, your logic is correct, but it is poorly implemented, once you have filtered the data, it is only rendering a new component:

import { EmailIcon, LocationIcon } from "./assets/FormSvgIcons";
import React, { useEffect, useState } from "react";

export default function SettingsForm() {
  const [stateList, setStateList] = useState([]);

  useEffect(() => {
    fetch("https://servicodados.ibge.gov.br/api/v1/localidades/estados/")
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        console.log(data);
        setStateList(data);
      });
  }, []);

  return (
    <form>
      <div className="user-country">
        <label className="white-label">Local</label>
        <div className="input-icon-wrapper">
          <div className="icon-input w-embed">
            <LocationIcon />
          </div>
          <select
            className="select-field white-select w-select"
            id="locationField"
            name="locationField"
            onChange={handleLocation}
          >
            {stateList.map((state) => {
              return <CreateDropdownOptions state={state} />;
            })}
          </select>
        </div>
      </div>
    </form>
  );
}

function CreateDropdownOptions({ state }) {
  return (
    <option key={state.id} value={state.sigla}>
      {state.sigla}
    </option>
  );
}

I recommend using a component for each option, this will make it easier if you later need to do some action on the

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading