Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

207
Visualizações
React get value from select dropdown populated from API

I have a select component:

<Select}>
    {data &&
        data.map((survey) => (
            <Option key={survey.id} value={survey.id}>
                {survey.name}
            </Option>
        ))
     }
</Select>

The data array is coming from an API fetch using axios, which is then saved in the state data:

const [data, setData] = useState([]);

How do I grab the selected value and display it?

I tried adding an onChange handler to the component and save the e.target.value in a separate piece of state:

onChange={e => setInput(e?.target?.value)}

However, I'm getting an error that value is undefined. I suspect it's because the data hasn't loaded yet.

How do you get the selected value from the options when the options are coming from an API? (i.e., dynamic dropdown)

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Try like this :

  const [data, setData] = useState([]);
  const handleChange = (e) => {
    console.log(e.target.value);
    setData(e.target.value);
  };

   <select onChange={handleChange}>
      {dataArr &&
        dataArr.map((survey) => (
          <option key={survey.id} value={survey.id}>
            {survey.name}
          </option>
        ))}
    </select>

Example : Example

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to define a new state and set it in onChange handler to show the selected data at somewhere else.

Define it as:

const [selectedValue,setSelectedValue] = useState()

Then, set it:

const handleChange = (e) => { 
    setSelectedValue(e.target.value)
}

it is now available to use anywhere in this component.

Here is an example:

import React, { useState, useEffect } from 'react';

export default function App() {
  const [data, setData] = useState([]);
  const [selectedValue,setSelectedValue] = useState()

// this useEffect is just a simulator for api response, you do not need this useEffect, 
// instead just call your api and set the data with your awaited response
  useEffect(()=>{ 
    setTimeout(()=> {
      setData([ 
        { name: 'first Option', id: 'ID of first option'},
        { name: 'Second Option', id: 'ID of second option' }
      ])
    },[2000])
  },[])

  const handleChange = (e) => { 
    console.log(e.target.value); // maybe print the value to check
    setSelectedValue(e.target.value)
  }
  
  return (<div>
    <select onChange={handleChange}>
      {data &&
        data.map((survey) => (
          <option key={survey.id} value={survey.id}>
            {survey.name}
          </option>
        ))}
    </select>
    {selectedValue ? <div>Selected value:  {selectedValue} </div> : ''}
  </div>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Can you confirm that the value attribute on the option tag is properly set and it has the value you want it to have.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda